daedsidog
daedsidog

Reputation: 1773

Android Studio: Different Buttons With Same ID?

I have a special button that appears in multiple areas in the same activity that has a resetting functionality. Since AS didn't allow me to declare multiple instances of that button in the same activity with the same ID name, I was wondering if it was possible to recreate that functionality in a different way.

What I have now is 3 different buttons, appropriately named Reset, with the IDs of reset1,reset2,reset3;

To handle their use, I just have a switch statement that looks like this (pseudo):

switch(button){
  case reset1:
  case reset2:
  case reset3:
     doSomething();
     break;
}

To me, it would appear simpler to just use a single ID for all those buttons. Why can't I do that? What are the risks? Is there any alternative to the method I'm currently using?

Upvotes: 0

Views: 2079

Answers (2)

drWisdom
drWisdom

Reputation: 512

Create a single method in your activity and then reference that method with each of your button via the onClick attribute of button. Like this:

<Button
        android:id="@+id/reset1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Reset"
        android:onClick="onReset"/> //Check this
<Button
        android:id="@+id/reset2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Reset"
        android:onClick="onReset"/>
<Button
        android:id="@+id/reset3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Reset"
        android:onClick="onReset"/>

Now in your MyActivity.java create onReset method as:

public void onReset(View v){
//do something.
}

Remember that the method needs to be public and have View as a parameter. You don't even need to assign id's to these buttons if not needed for another purpose.

Upvotes: 2

Ridcully
Ridcully

Reputation: 23655

Instead of that switch statement, you can assign the same OnClickListener to all three buttons:

OnClickListener listener = new OnClickListener() {
    public void onClick(View view) {
        doSomething();
    }
}
findViewById(R.id.reset1).setOnClickListener(listener);      
findViewById(R.id.reset2).setOnClickListener(listener);
findViewById(R.id.reset3).setOnClickListener(listener);

Upvotes: 1

Related Questions