Best practice for defining button events in android Best practice for defining button events in android android android

Best practice for defining button events in android


Why not registering onClick event in the XML layout and then handle it in the code. This is how I would do it:

<Buttonandroid:id="@+id/my_btn"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Click me"android:onClick="onBtnClicked"></Button>

and now create a method that would handle clicks

public void onBtnClicked(View v){    if(v.getId() == R.id.my_btn){        //handle the click here    }}

Alternatively, you can set the OnClickListener individually for each item in the code. Then use the if/else or switch statements to determine the origin.

This way you can have one method that handles all buttons from one layout.

UPDATE:
Although this is a valid approach I would strongly recommend the second option. It's cleaner and easier to maintain especially when you work with fragments.


Here is the best approach with code:

  public class MyTest extends Activity implements OnClickListener{    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);     //... some other code here to init the layout        Button btn1 = (Button)findViewById(R.id.button1);        Button btn2 = (Button)findViewById(R.id.button2);        btn1.setOnClickListener(this);        btn2.setOnClickListener(this);    }    @Override    public void onClick(View v) {        switch(v.getId()){            case R.id.button1:                break;            case R.id.button2:                break;        }    }}

The new class with an interface is only good if you want to decouple the implementation (when you want to use the same class code somewhere else, move it to another seperate class file etc..) but in general if you are doing things connected with the current activity you are on and the onClick implementations depend on it running with reference to the objects defined there you should definitely use the method i suggested.

Creating class interfaces is only good when you want to achieve communication between seperate classes or activities and keep things apart. other than that its a bad practice creating subclasses for this.


this is the best approach

@Overridepublic void onCreate(Bundle savedInstanceState) {        button1.setOnClickListener(onClickListener);        button2.setOnClickListener(onClickListener);        button3.setOnClickListener(onClickListener);}private OnClickListener onClickListener = new OnClickListener() {     @Override     public void onClick(final View v) {         switch(v.getId()){             case R.id.button1:                  //DO something             break;             case R.id.button2:                  //DO something             break;             case R.id.button3:                  //DO something             break;         }   }};