I find myself doing things like this all the time:
Button button1 = (Button) findViewById(R.id.button1);
Button button2 = (Button) findViewById(R.id.button2);
Button button3 = (Button) findViewById(R.id.button3);
button1.setOnClickListener(menuButtonListener);
button2.setOnClickListener(menuButtonListener);
button3.setOnClickListener(menuButtonListener);
...
and
private OnClickListener myButtonListener = new OnClickListener() {
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.button1 :
...
Is there a better way to set the OnClickListener?
I think in case, when your buttons are not in Activity but in FragmentDialog, etc., this can help
If you want to do less code for click listeners you have this lib [http://jakewharton.github.io/butterknife/]
you just have to do this
Have your class implement `View.OnClickListener', like
Gettin @foenix answer, you can simply do something like:
It should be noted, that
requires at least Andoid SDK 1.6. So if you want your App to be accessible to as big audience as possible, you probably want to write your App against Android 1.6. Unless your App requires a feature which is only available in 1.6+. So while your first attempt is bit more of work, it has greater backwards compatibility. I usually do it the way you do, to keep my Apps 1.5 comptaible.
Edit: It's easy to overlook this, if you set up Android 2.2 as SDK in your projects settings, but set minSDK version to 3 (1.5), as it doesn't give compiler errors.
You can also set it in your layout xml using the android:onclick attribute.
Then in your activity class add the onClick method.
Here's the documentation.