How to get a button Id in of a clicked button? - java

I have a couple of buttons I want to make a computation on, so I want to get the ID of the particular button clicked so I can perform an operation on.
I have configured the id for all my buttons in my XML file.
I hope i can get help here.
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_marginTop="15dp"
android:textSize="45dp"
android:gravity="center_horizontal"
android:textColor="#color/colorPrimaryDark"
android:id="#+id/displayCalc"
android:text="0"></TextView>
<Button
android:id="#+id/button_one"
android:layout_width="70dp"
android:layout_height="wrap_content"
android:text="1"
android:onClick="one"/>
<Button
android:id="#+id/button_two"
android:layout_width="70dp"
android:layout_height="wrap_content"
android:text="2"
android:onClick="two"/>
<Button
android:id="#+id/button_three"
android:layout_width="70dp"
android:layout_height="wrap_content"
android:text="3"
android:onClick="three"/>
<Button
android:id="#+id/button_add"
android:layout_width="70dp"
android:layout_height="wrap_content"
android:text="+"
android:textColor="#color/design_default_color_primary_dark"
android:textSize="18sp"
android:onClick="calcAdd"/>
</LinearLayout>

Your question is a little strange. If I got it correctly you want to know which button is clicked in Java/Kotlin and perform some operation based on buuton id.
If that is what you want:
Implement View.OnClickListener in your activity or fragment related to this xml.
Implement onCLick(View) method.
Now you can use when (kotlin) or switch (java) to find the clicked button id.
class MainActivity : AppCompatActivity(), View.OnClickListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button_one.setOnClickListener(this)
button_two.setOnClickListener(this)
}
override fun onClick(v: View) {
when (v.id) {
R.id.button_one -> {
//TODO (do something for button with id button_one)
}
R.id.button_two -> {
//TODO (do something for button with id button_two)
}
}
}
}

You have defined in the XML file for the Button with id button_one with this attribute:
android:onClick="one"
that the listener will be a method named one, so all you have to do is create that method inside your activity like this:
public void one(View view) {
<your code goes here>
}
If you want to refer to the Button inside that method you can do it like this:
Button button = (Button) view;
and if you want its id:
int id = button.getId();
So create 4 methods (like the one above) inside your Activity class for all 4 buttons: one(), two(), three() and calcAdd().

say you're doing something like that
Button buttonOne = findViewById(R.id.button_one); //now you have access to the button that is in your layout
buttonOne.setOnClickLister(new View.OnClickListener(){ // i hope you understand anonymous inner class
#Override
public void onClick(View v){ //now when your button is clicked this method is called
//and you passed v in argument which is nothing but your button
//you're passed a View object and not a out of the box button because the
//View.OnClickListener can be implemented on any view if you want to call button
//specific method on it you cast it to a button , because you know it is a button
//inside
v.getId() //gives you the id of your button which you wanted
}
}
Tell me there is still some confusion .

Related

Android button not clickable when turning visible

Hi Im posting this after not finding any possible answer here.
I have an invisible LinearLayout LL1 in a fragment that I turn visible when a recylerView data is empty, that LL1 has a button on it. The problem is simply that the button is not clickable ! I tried setting the listener in different ways but still not working. Here's the code below:
Here's the xml file:
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".activity.main.MainActivity"
android:layout_marginTop="3dp">
<LinearLayout
android:id="#+id/msg_emty_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:visibility="gone"
android:orientation="vertical">
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:src="#drawable/ic_empty_box" />
<TextView
android:layout_marginTop="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Aucune vente n'a été trouvée !"
android:textSize="15dp"
android:layout_gravity="center_horizontal"
android:textColor="#color/greydark"/>
<Button
android:id="#+id/btnAddSale"
android:layout_marginTop="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Créer une vente"
android:textColor="#color/whiteTextColor"
android:background="#drawable/centre_button">
</Button>
</LinearLayout>
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipe_refresh_db"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view_sale_list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.support.v4.widget.SwipeRefreshLayout>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab_add_db"
android:layout_margin="20dp"
android:layout_gravity="bottom|end"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/colorAccesGreen"
android:src="#drawable/ic_edit"/>
</android.support.design.widget.CoordinatorLayout>
And here's the java:
private void generateSaleList(ArrayList<Sale> saleArrayList, View view) {
if(saleArrayList.isEmpty()){
getActivity().setTitle("Ventes sur portable");
msgLayout.setVisibility(View.VISIBLE);
creatSaleBtn = (Button) view.findViewById(R.id.btnAddSale);
creatSaleBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "Button clicked !", Toast.LENGTH_LONG).show();
}
});
creatSaleBtn.setClickable(true);
}else{
msgLayout.setVisibility(View.GONE);
recyclerView_db = view.findViewById(R.id.recycler_view_sale_list);
adapter_db = new SaleAdapter((ArrayList<Sale>) Utils.sortArray(saleArrayList),this,1,getContext(),this);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView_db.setLayoutManager(layoutManager);
recyclerView_db.setAdapter(adapter_db);
adapter_db.notifyDataSetChanged();
}
}
Do you guys see what's causing this weird problem ?
You can try with requestFocusFromTouch()
Call this to try to give focus to a specific view or to one of its
descendants.
msgLayout.setVisibility(View.VISIBLE);
creatSaleBtn = (Button) view.findViewById(R.id.btnAddSale);
creatSaleBtn.requestFocusFromTouch();
Hide your RecyclerView when there's no items (set visibility to gone). The problem is that it's capturing the clicks, since it's placed on top of the button.
as u said in comments you not using creatSaleBtn.setClickable(false); anywhere, then you have to hide the recyclerView using recyclerView_db.setVisibility(View.GONE);
why? because it by default fits the full-screen due too match_parent for width and height.
please add recyclerView_db.setVisibility(View.GONE); in the saleArrayList.isEmpty() check
so your new code will be :
if(saleArrayList.isEmpty()){
recyclerView_db.setVisibility(View.GONE);
getActivity().setTitle("Ventes sur portable");
msgLayout.setVisibility(View.VISIBLE);
creatSaleBtn = (Button) view.findViewById(R.id.btnAddSale);
creatSaleBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "Button clicked !", Toast.LENGTH_LONG).show();
}
});
creatSaleBtn.setClickable(true);
}
SwipeRefreshLayout's visibility should be GONE after recyclerview is empty.
of coarse recyclcerview is empty but it is still visible so your click events are caught by SwipeRefreshLayout witch is defined on top of LL1.
EDIT
instead of recyclerview, set swipe_refresh_db visibility to gone cos I doubt recyclerview is a child of swipe_refresh_dd so if you set recyclerview's visibility to gone, swipe_refresh_db is still visible and gets click events.
give it a try

Button setOnClickListener is not working only for one button

I have two different buttons in my activity, and an if statement to show them...
My if statement is working well and show the right button, but one of those buttons is not doing anything when I click on it! (Actually, it's not clickable at all!)
if (isNeeded)
{
// buttonImportant is not clickable
buttonImportant.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("LOG", "Clicked!"); // Even this log won't work!
Intent intentDetailsActivity = new Intent(MainActivity.this, DetailsActivity.class);
intentDetailsActivity.putExtra("extraPosition", String.valueOf(position));
startActivity(intentDetailsActivity);
}
});
linearLayoutImportant.setVisibility(View.VISIBLE); // This line is working
}
if (!isNeeded)
{
// buttonNormal is working well!
buttonNormal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
linearLayoutNormal.setVisibility(View.GONE);
Intent intentDetailsActivity = new Intent(MainActivity.this, DetailsActivity.class);
intentDetailsActivity.putExtra("extraPosition", String.valueOf(position));
startActivity(intentDetailsActivity);
}
});
linearLayoutNormal.setVisibility(View.VISIBLE); // And this one is not working too!
}
The problem is, it won't return any error or log, to know what's the problem! It's log I disabled the button... (which I didn't)
I checked if it's for declarations, but everything is declared well...
I checked the XML, there's no problem there either:
<LinearLayout
android:id="#+id/linearLayoutImportant"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="50dp"
android:layout_centerInParent="true"
android:gravity="center_vertical|center_horizontal"
android:orientation="vertical"
android:visibility="gone" >
<TextView
android:id="#+id/textViewImportant"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical|center_horizontal"
android:text="#string/important"
android:textSize="20sp"
android:textColor="#FFFFFF"
android:textStyle="bold" />
<Button
android:id="#+id/buttonImportant"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="#string/details" />
</LinearLayout>
...
...
<LinearLayout
android:id="#+id/linearLayoutNormal"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_marginTop="25dp"
android:orientation="vertical"
android:visibility="gone" >
<Button
android:id="#+id/buttonClose"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_gravity="end"
android:background="#android:drawable/ic_menu_close_clear_cancel" />
<TextView
android:id="#+id/textViewNormal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:layout_gravity="center_horizontal"
android:gravity="center_vertical|center_horizontal"
android:text="#string/normal"
android:textStyle="bold" />
<Button
android:id="#+id/buttonNormal"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_margin="2dp"
android:layout_gravity="center_horizontal"
android:text="#string/details" />
</LinearLayout>
EDIT:
Here's the declarations:
LinearLayout linearLayoutImportant, linearLayoutNormal;
Button buttonImportant, buttonClose, buttonNormal;
...
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearLayoutImportant = (LinearLayout) findViewById(R.id.linearLayoutImportant );
buttonImportant = (Button) findViewById(R.id.buttonImportant);
buttonClose = (Button) findViewById(R.id.buttonClose);
buttonClose .setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
linearLayoutNormal.setVisibility(View.GONE);
}
});
buttonNormal = (Button) findViewById(R.id.buttonNormal);
linearLayoutNormal = (LinearLayout) findViewById(R.id.linearLayoutNormal);
}
EDIT 2:
Alright guys, maybe I didn't made it clear...
That isNeeded is a variable and I control it from another place...
When I make it false, the second if will get executed very well, and when I make it true, the first if will execute too, but only the button is not clickable!
EDIT 3:
I also checked .setEnabled(true); or .setClickable(true);, still not working... :/
SOLVED:
I used the HierarchyViewer and found the problem. The problem was in XML... I had a ListView on top of second button, but it was empty, so I thought nothing's there...
Sorry everybody...
I used the HierarchyViewer and found the problem. The problem was in XML... I had a ListView on top of second button, but it was empty, so I thought nothing's there...
Sorry everybody...
Try without the if statement in order to know if is a validation problem and you're only setting one listener
The boolean variable isNeeded can take only one of the two values, either true or false. Therefore only one of the if conditions will be executed.
Since only one of the condition is true, you are only setting an onClickListener to one of the buttons and thus the other button won't be clickable and the log message within the onClick method won't be visible in the logs.
Hope this answered your question.
All the best :)
set isNeeded = true before
if (isNeeded)
{
// buttonImportant is not clickable
buttonImportant.setOnClickListener(new View.OnClickListener() {
then test it again.
Good lucky!
There was an error posting my ans so i have taken a screenshot of it. Please review it for your answer

How to create two android button using android studio

I am just getting into android apps, and I have yet to find a tutorial that explains in detail of how to do anything.Can someone show me the code on how to create two buttons (sign in and sign up) in android ?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loginButton=(Button)findViewById(R.id.button);
button.setOnClickListener(LogInListener);
signUpButton=(Button)findViewById(R.id.button2);
button2.setOnClickListener(SignUpListener);
}
private OnClickListener LogInListener=new OnClickListener()
{
public void onClick(View v)
{
}
}
Is this the correct way to implement? thanks
activity_main.xml
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Log In"
android:id="#+id/button"
android:layout_marginTop="61dp"
android:layout_below="#+id/textView3"
android:layout_toStartOf="#+id/button2"
android:layout_toLeftOf="#+id/button2" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sign UP"
android:id="#+id/button2"
android:layout_alignTop="#+id/button"
android:layout_alignLeft="#+id/editText2"
android:layout_alignStart="#+id/editText2"
android:layout_marginLeft="48dp"
android:layout_marginStart="48dp" />
EDIT:
Now that you have edited your question, you just need to do one more thing to declare your Buttons as instance variables. Declare them outside of all methods (onCreate) but inside the mainActivity.
PRE EDIT:
I'll show you what your main activity (Java class) and what your layout (XML file) should look like:
Main Activity:
public class MainActivity extends AppCompatActivity {
Button signIn, signUp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
signIn = (Button) findViewById(R.id.'idOfButtonFromXMLLayout');
signUp = (Button) findViewById(R.id.'idOfButtonFromXMLLayout');
//Looking at my XML code, the signIn id would be R.id.signInButton
}
The findViewById method is inherited from the AppCompatActivity class, all activities extend the AppCompatActivity class. Older versions of android just extended the Activity class.
The findViewById method takes an int parameter more specifically an id.
The reason a cast is required is because the findViewById method as you would assume returns a type of View, this is then casted to a button.
XML Layout File:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<Button
android:id="#+id/signInButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sign In"
<!-- Complete Layout Details--> />
<Button
android:id="#+id/signUpButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/signUpText"
<!-- Complete Layout Details--> />
</RelativeLayout>
In the code above I have represented the text of the buttons in two ways...
1) Hard-coded string "Sign In"
2) String resource "#string/signUpText
It is good practice to change your hard-coded strings to the latter format.
If you're new at Android Development some things are just confusing. I would create buttons by doing this:
Define Button in your XML File.
Add Listener to your Button.
Don't forget to add id attribute to your Button.
i would do it this way.
LAYOUT XML FILE
<Button
android:id="#+id/buttonOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button One" />
<Button
android:id="#+id/buttonTwo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 2" />
MainActivity.java
public class MainActivity extends AppCompatActivity implements View.onClickListener {
private Button buttonOne;
private Button buttonTwo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonOne = (Button) findViewById(R.id.buttonOne); // id located in your xml file
buttonOne.setOnClickListener(this);
buttonTwo = (Button) findViewById(R.id.buttonTwo);
buttonTwo.setOnCliclListener(this);
}
private void onClick(View v){
switch(v.getId()) {
case r.id.buttonOne: {
// action when buttonOne is clicked
break;
}
case r.id.buttonTwo: {
// action when buttonTwo is clicked
break;
}
}
}
To create a button, you have to code in your xml file, or drag it in your Design view which will do that for you
Which will auto-magicly do this for you, with auto generated values.
-to name your button edit android: text
-edit android: id to edit the "key" that connects your button design in xml to java
If you want to use your button for things like onclicklisteners and such, you will need to "import" it into your java code, like so. The android: id ="#/<>value"and findViewById(R.id.) should be the same (though its not in the photos)
Now simply do this again for every button you want and change the values to your needs. Hope I helped.

click toggle button programmatically in android

hello i have a toggle button like this :
<RadioGroup android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:orientation="horizontal">
<ToggleButton android:id="#+id/detailed_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/detailed_view"
android:textOff="#string/detailed_view"
android:textOn="#string/detailed_view"
android:onClick="viewChange" />
<ToggleButton android:id="#+id/main_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/main_view"
android:textOff="#string/main_view"
android:textOn="#string/main_view"
android:checked="true"
android:onClick="viewChange"
/>
</RadioGroup>
and i have the function viewChange like this:
public void viewChange(View v){
int id=v.getId();
if(id==R.id.main_view){
//do some thing with main view
}else if(id==R.id.detailed_view){
do something with detailed view
}
}
Now i need to call this function ViewChange(View v) and set the parameter v programatically, i means that i want to click this toggle button programatically and specify which view i want to click.
You can programmatically change the state of the ToggleButton by using the setChecked method:
toggleButton.setChecked(true or false)
More information on the ToggleButton may be found in the API reference: http://developer.android.com/guide/topics/ui/controls/togglebutton.html
make use of
.setChecked()
property.
Ref
http://developer.android.com/reference/android/widget/ToggleButton.html#setChecked%28boolean%29

Button is not calling OnClickListener with first click

I am trying to develop a Log in page, where I have Username, password and a button. When I click the button for the first time, nothing happens, but when I click the button for the second time, then it works properly. I am confused, why it is happening ?
activity_login.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/splash_bg"
tools:context=".LoginActivity" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:orientation="vertical"
android:layout_margin="30dp" >
<EditText
style="#style/EditText1"
android:id="#+id/userEditText"
android:layout_marginBottom="50dp"
android:inputType="textNoSuggestions"
android:singleLine="true"
android:hint="username" />
<EditText
style="#style/EditText1"
android:id="#+id/passEditText"
android:inputType="textPassword"
android:layout_marginBottom="50dp"
android:hint="password" />
<Spinner
android:id="#+id/locationSpinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:popupBackground="#ffffff"
style="#style/EditText1"
android:layout_marginBottom="50dp" />
<Button
style="#style/Button1"
android:focusable="true"
android:focusableInTouchMode="true"
android:onClick="onLoginClick"
android:text="continue"
/>
loginActivity.java
#SuppressLint("DefaultLocale")
public void onLoginClick(View view) {
String username = mUserEditText.getText().toString();
String password = mPassEditText.getText().toString();
String location = mLocationData.get(
mLocationSpinner.getSelectedItemPosition()).toLowerCase();
if (username.isEmpty() || password.isEmpty()) {
CreatorMessenger
.getInstance()
.showMessage(this, "Error!!",
"You need to enter username and password both to continue!!");
return;
}
User user;
user = new User(username);/*
* }
*/
user.setLocation(location);
AppManager.getInstance().setLoggedInUser(user);
APICaller.getInstance().login(username, password, location);
}
You are setting android:focusableInTouchMode="true"
Hence on 1st click it receives focus.
Refer Android button - How to set focusable to true and still accept onClick listener on first click?
Set this -
android:focusableInTouchMode="true"
to this -
android:focusableInTouchMode="false"
on button.
Explanation - If you'll make the button focusable then on first click the focus is passed to the button, then the click is passed on second touch. EditText is a focusable View which gains focus first and therefore other views must first regain the focus from EditText, unless they do not need focus to work, just like buttons. If you just need the OnClick function, then you don't need focus, so you can spre one extra click.
PS: Although it shouldn't require, but setting android:focusable to false will help too, if the first one doesn't work.
Yes Yes I got the answer, after a lot of RND, I got the solution, I just need to implement setOnClickListener(), and setOnFocusChangeListener(). So I am putting here the solution.
ActivityLogin.java
buttonLogin= (Button) findViewById(R.id.buttonLogin);
buttonLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d("hello", "hellow");
String username = mUserEditText.getText().toString();
String password = mPassEditText.getText().toString();
String location = mLocationData.get(mLocationSpinner.getSelectedItemPosition()).toLowerCase();
if(username.isEmpty()||password.isEmpty()){
popbox();
return;
}
User user;
user = new User(username);
user.setLocation(location);
AppManager.getInstance().setLoggedInUser(user);
APICaller.getInstance().login(username, password, location);
}
});
buttonLogin.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
v.performClick();
}
}
});
}
activity_login.xml
<Button
android:id="#+id/buttonLogin"
style="#style/Button1"
android:text="continue"
/>
if in your xml in button, or img, or liner layout has:
android:focusableInTouchMode="true"
To resolve, just
remove this.
I suggested to use request focus in the "onCreate()" method.
When you using android:focusableInTouchMode="true" you may don't want the focus catch by an 'EditText' field.
For example:
1. An activity has a view contain -> android:focusableInTouchMode
2. You open a Fragment Dialog, but the back button need click two times to fire it.
3. You should call requestFocus() after the Fragment Dialog onCreateView()

Categories

Resources