Question :
Is there a different way (“syntax”) to “set” a listener on an object in Android? For example, I only know this form:
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
activity.onBackPressed(-1);
}
});
Answer :
You can also assign clickEvent
to xml :
<Button
android_layout_height="wrap_content"
android_layout_width="wrap_content"
android_text="OK"
android_onClick="onClick" />
In Activity implement a method called onClick that receives View :
public void onClick(View v) {
activity.onBackPressed(-1);
}
The name of the method can be any one, as long as it is the same as that in xml .
Another way is Activity to implement the interface OnClickListener
:
public class Main extends Activity implements OnClickListener {
Button button1;
Button button2;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button1 = (Button) this.findViewById(R.id.Button1);
button1.setOnClickListener(this);
button2 = (Button) this.findViewById(R.id.Button2);
button2.setOnClickListener(this);
}
public void onClick(View v) {
if((Button)v == button1{
//O button1 foi clicado
}
if((Button)v == button2{
//O button2 foi clicado
}
}
}