1) The first, but also the longest-to-see method of addition (click on the button for example)
1 Button btn = (button) Findviewbyid (R.id.mybutton);
2 btn. Setonclicklistener (New View.onclicklistener () {
3 Public void OnClick (View v) {
4//do Something
5 }
6 });
2) Second, the following method is slightly simpler than the previous one, allowing multiple buttons to share a single listener. To control the response to different button click events via the switch:
1 Button btn = (button) Findviewbyid (R.id.mybutton);
2 Button btn2 = (button) Findviewbyid (R.id.mybutton2);
3 Btn.setonclicklistener (handler);
4 Btn2.setonclicklistener (handler);
5 View.onclicklistener handler = View.onclicklistener () {
6 Public void OnClick (View v) {
7 switch (V.getid ()) {
8
9//do Something
Ten break ;
11
//do something
Break ;
+ }
}
3) Third, directly clicklistener bundle the views element in the XML layout, the listener method defined in the program requires a parameter with a view type:
1 <?xml version= "1.0" encoding= "Utf-8"?>
2 <linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"
3 android:orientation= "vertical" android:layout_width= "fill_parent"
4 android:layout_height= "Fill_parent" >
5 <textview android:layout_width= "Fill_parent"
6 android:layout_height= "wrap_content" android:id= "@+id/text"
7 android:text= "@string/hello"/>
8 <button android:id= "@+id/mybutton" android:layout_height= "Wrap_content"
9 android:layout_width= "wrap_content" android:onclick= "Mybuttonlistener" ></Button>
Ten </LinearLayout>
Java code:
1 Button btn = (button) Findviewbyid (R.id.mybutton);
3 public void Mybuttonlistener (View target) {
4//do Something
5 }
How to add a view's Setonclicklistener