Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to go about multiple Buttons and OnClickListeners

Tags:

android

button

I have in 16 Buttons (numbers, plus, minus etc) in my layout XML file.

I'm wondering how to check which button was pressed.

My idea is, that I will for each button use onClick() method but this method is a bit impractically, because I will have 16 of these onClick() methods one for each Button.

Is there a more elegant way?

like image 518
user1946705 Avatar asked Apr 13 '11 08:04

user1946705


3 Answers

You can deal with them all in a single class that implements OnClickListener, or within the activity class if you like...

import android.view.View.OnClickListener;

   public class MyActivity extends Activity implements OnClickListener {

      @Override public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);
         Button buttonA = (Button) findViewById(R.id.buttonA);    
         buttonA.setOnClickListener(this);
         Button buttonB = (Button) findViewById(R.id.buttonB); 
         buttonB.setOnClickListener(this);
      }

   //etc... etc...

   public void onClick(View v) {

      switch (v.getId()) {
         case R.id.buttonA: 
          // do something
          break;
         case R.id.buttonB:
          // do something else
          break;
      }
   }

}
like image 173
user433579 Avatar answered Oct 24 '22 05:10

user433579


You can use one handler that you do not define as anonymous inner class, but in a separate class. onClick() will get the view passed in and you can select from it.

public class MyActivity implements OnClickListener {
    public void onClick(View v) {
       Button b = (Button)v;
       // do what you want 
    }

    ...
}

and then in your layout.xml just put for each button

<Button android:id=".."
        android:onClick="onClick"
like image 42
Heiko Rupp Avatar answered Oct 24 '22 05:10

Heiko Rupp


Sure. Create an array of your button-ids and assign them the same listener (an implementation of View.OnClickListener - defined as separate class, not as anonymous class) in a loop. In the listener you can check which is the pressed button (by comparing view parameter in onClick() method).

In activity:

MyOnClickListener myListener = new MyOnClickListener();
for (int id : buttonIdArray)
    ((Button)findViewById(id)).setOnClickListener(myListener);

In the onClick method:

int id = view.getId();
switch (id)
{
case ...:
// Do stuff
case ...:
// Do different stuff
}
like image 28
MByD Avatar answered Oct 24 '22 04:10

MByD