Cinco maneiras de conectar um ouvinte de evento é um ótimo artigo que mostra as várias maneiras de configurar um único ouvinte de evento. Deixe-me expandir isso aqui para vários ouvintes.
1. Classe Membro
public class main extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//attach an instance of HandleClick to the Button
HandleClick handleClick = new HandleClick();
findViewById(R.id.button1).setOnClickListener(handleClick);
findViewById(R.id.button2).setOnClickListener(handleClick);
}
private class HandleClick implements OnClickListener{
public void onClick(View view) {
switch(view.getId()) {
case R.id.button1:
// do stuff
break;
case R.id.button2:
// do stuff
break;
}
}
}
}
2. Tipo de interface
public class main extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.button1).setOnClickListener(handleClick);
findViewById(R.id.button2).setOnClickListener(handleClick);
}
private OnClickListener handleClick = new OnClickListener() {
public void onClick(View view) {
switch (view.getId()) {
case R.id.button1:
// do stuff
break;
case R.id.button2:
// do stuff
break;
}
}
};
}
3. Classe interna anônima
public class main extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
public void onClick(View view) {
// do stuff
}
});
findViewById(R.id.button2).setOnClickListener(new OnClickListener() {
public void onClick(View view) {
// do stuff
}
});
}
}
4. Implementação na atividade
public class main extends Activity implements OnClickListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.button1).setOnClickListener(this);
findViewById(R.id.button2).setOnClickListener(this);
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.button1:
// do stuff
break;
case R.id.button2:
// do stuff
break;
}
}
}
5. Atributo no layout da vista para eventos OnClick
public class main extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void HandleClick(View view) {
switch (view.getId()) {
case R.id.button1:
// do stuff
break;
case R.id.button2:
// do stuff
break;
}
}
}
E em xml:
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="HandleClick" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="HandleClick" />