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