Android: Attaching ClickListeners Declaratively

If you define a click listener for - say - a button in an android Activity, then you basically have three different possibilities.

The "old" Java like Way

This is the normal programmatic approach; you retrieve the button object and attach the click listener by implementing the according interface.
Button myButton = (Button)findViewByid(R.id.myButton);
myButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//TODO your logic
}
});
Nothing special, right? However this will lead to quite messy code if you have multiple buttons. The main point though is that we're on a mobile. Although the devices get more and more powerful, CPU and memory are still an issue. What this code does is basically to create an anonymous object implementing the View.OnClickListener interface and directly passing it to the myButton object. This has the disadvantage that we're having one listener object per button which is not very memory efficient.
The next solution provides a more optimized way.

Shared Listener

The following solution is the suggested one for registering listeners. It avoids creating multiple objects, but shares the same listener for different buttons.
public class MyAndroidActivity extends Activity implements OnClickListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
...
Button myButton = (Button)findViewById(R.id.myButton);
myButton.setOnClickListener(this);
...
}

@Override
public void onClick(View v){
switch(v.getId()){
case R.id.myButton:
//TODO button logic
break;

default:
break;
}
}
}
This is self-explanatory, I guess. What still puzzles me here is that if I have more buttons, I always again need to retrieve the button and attach the listener, for each of them. This is cumbersome, so I personally favor the next, declarative approach.

Declarative Approach

Android provides another way of declaring your listeners, declaratively in your layout xml file.
<Button android:id="@+id/myFirstButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="First button"
android:onClick="myOnClick"/>
Then in your corresponding Activity code you need to implement the method, just as in the example before:
public void myOnClick(View v){
switch(v.getId()){
case R.id.myButton:
//TODO button logic
break;

default:
break;
}
}
This solution allows you to save the tedious and repetitive registering of the listeners.
Kindle

Comments

0

Your ad here?