Android: Attaching ClickListeners Declaratively
2 min read
2 min read
If you define a click listener for - say - a button in an android Activity, then you basically have three different possibilities.
Button myButton = (Button)findViewByid(R.id.myButton);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
myButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//TODO your logic
}
});
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.public class MyAndroidActivity extends Activity implements OnClickListener{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.
@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;
}
}
}
<Button android:id="@+id/myFirstButtonThen in your corresponding Activity code you need to implement the method, just as in the example before:
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="First button"
android:onClick="myOnClick"/>
public void myOnClick(View v){This solution allows you to save the tedious and repetitive registering of the listeners.
switch(v.getId()){
case R.id.myButton:
//TODO button logic
break;
default:
break;
}
}