Android: Grouping onClickListeners together by implementation in an activity
Here is a quick tip for better organisation of your program by grouping all onClickListeners into a simple switch statement.
The problem
If you have lots of buttons or view that you are linking to OnClickListener events you can quickly end up with some cumbersome code. This can be changed very simply by implementing a method in your activity and switching between View ID’s.
Below is an example the typical method for creating an OnClickListener for a View.
final ImageButton Ibutton = (ImageButton) findViewById(R.id.button_1);
Ibutton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(testActivity.this, "Button 1 pressed ", Toast.LENGTH_SHORT).show();
}
});
final ImageButton Ibutton2 = (ImageButton) findViewById(R.id.button_2);
Ibutton2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(testActivity.this, "Button 2 pressed", Toast.LENGTH_SHORT).show();
}
});
The Solution
We can get our activity to handle the OnClick events itself, we do this we implementing OnClickListener:
public class testActivity extends Activity implements OnClickListener {
If your write this in eclipse you can hover over the error this produces and click Add unimplemented methods to automatically create a stub for the next part.
We now create our buttons similar to before, but for the setOnClickListener we pass this as an argument, so that our implemented method is called.
ImageButton Ibutton = (ImageButton) findViewById(R.id.button_1); Ibutton.setOnClickListener(this); ImageButton Ibutton2 = (ImageButton) findViewById(R.id.button_2); Ibutton2.setOnClickListener(this);
We now create the implemented method for our activity (onClick) and we use a switch statement to find which View fired the onclick event and preform an action accordingly.
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.button_1:
// action to preform on button 1
Toast.makeText(testActivity.this, "Button 1 pressed ", Toast.LENGTH_SHORT).show();
break;
case R.id.button_2:
// action to preform on button 1
Toast.makeText(testActivity.this, "Button 2 pressed ", Toast.LENGTH_SHORT).show();
break;
}
}
And it’s as simple as that!
Feel free to post comments or questions



Thanks Stealthcopter. This was a great halp ^_^
thx that really helps apps with a large amount of buttons
Its not working for me. My app is failing to load.
@Abhi Check your logcat for errors, usually explains what’s going wrong.
Nice way of keeping code clean, thanks a lot.
V nice. Makes things more readable and cuts down on total lines
Thanks, that’s really helpful.
One question, If you want to call two buttons in two differents layouts. Is the same code? Or I need to add something else.
Thanks for your replay!
thans for ur help….was good to see my small code started working thanx bro