1.XML Add listening properties, add the DoClick here.
1 <Button2 Android:id= "@+id/bt1"3 Android:layout_width= "Wrap_content"4 Android:layout_height= "Wrap_content"5 Android:onclick= "DoClick"6 Android:text= "xml add DoClick"7 Android:layout_above= "@+id/bt2"8 Android:layout_marginbottom= "47DP"9 />
1 Public voidDoClick (view view) {2 Switch(View.getid ()) {3 CaseR.ID.BT1:4Toast.maketext (mainactivity. This, "First Click event: XML Add DoClick", Toast.length_short). Show ();5 Break;6 7 }8 9}
Add the DoClick implementation method to the activity. The methods implemented in activity are the same as the attribute names added by XML, and are not recommended for actual development .
2. Anonymous inner class method implementation.
1 Button BT2 = (Button) Findviewbyid (R.ID.BT2); 2 Bt2.setonclicklistener (new View.onclicklistener () {3 @Override4 public void OnClick (View v) {5 Toast.maketext ( Mainactivity. This, "Second click event: Anonymous inner Class", Toast.length_short). Show (); 6 }7 });
3. Customize the Click event Implementation.
1Button BT3 =(Button) Findviewbyid (R.ID.BT3);2Bt3.setonclicklistener (NewMyListener ());
3 classMyListenerImplementsView.onclicklistener {4 @Override5 Public voidOnClick (View v) {6Toast.maketext (mainactivity. This, "Third method: Customizing Click events", Toast.length_short). Show ();7 }8}
4.Activity inherits View.onclicklistener, which implements the OnClick (view view) method by the activity.
1 Public classMainactivityextendsAppcompatactivityImplementsView.onclicklistener {2 @Override3 protected voidonCreate (Bundle savedinstancestate) {4 Super. OnCreate (savedinstancestate);5 Setcontentview (r.layout.activity_main);6Button bt4=(Button) Findviewbyid (R.ID.BT4);7Bt4.setonclicklistener ( This);8 }9 Ten @Override One Public voidOnClick (View v) { A Switch(V.getid ()) { - CaseR.ID.BT4: -Toast.maketext (mainactivity. This, the"Fourth Click event: Activity Inherits View.onclicklistener, and the onclick (view view) method is implemented by activity", - toast.length_short). Show (); - } - } +}
Note: The second, anonymous inner class is recommended in the case of a few buttons, whereas the fourth is recommended, and the activity inherits View.onclicklistener implementation.
Android button Four Click event Implementation mode