First, the use of anonymous internal classes to implement the Onclicklistener interface, Universal;
Second, let Mainactivity realize Onclicklistener interface, this method is suitable for having multiple components, so it is more convenient to use;
Define the OnClick method and the custom method in the corresponding component of the XML file;
Realization of the source code:
Package Com.example.clickbutton;import Android.os.bundle;import Android.app.activity;import android.view.Menu; Import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;import android.widget.toast;//here in order to use the second method, the Onclicklistener interface is implemented in the start activity, and the public class Mainactivity extends activity Implements Onclicklistener{private Button button,button2,button3,button4; @Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); button= (Button) Findviewbyid (R.id.button1); button2= (Button) Findviewbyid (R.id.button2); button3= (button) Findviewbyid ( R.id.button3); button4= (Button) Findviewbyid (r.id.button4); Button2.setonclicklistener (this);// The second way of Buttonbutton3.setonclicklistener (this);//The button//of the second way: using Anonymous inner class: Button.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {//TODO auto-generated method Stubtoast.maketext ( Mainactivity.this, "This is the first button", 1). Show ();}}); @OvErridepublic boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action bar if it is Prese Nt.getmenuinflater (). Inflate (R.menu.main, menu); return true;} The second kind: let Mainactivity implements Onclicklistener interface, so it can be written as follows: public void OnClick (View v) {//TODO auto-generated Method St Ubswitch (V.getid ()) {case R.id.button2:toast.maketext (mainactivity.this, "This is the second button", 1). Show (); break;case R.id.button3:toast.maketext (Mainactivity.this, "This is the third button", 1). Show (); break;default:break;}} The third is to define (BIND) an Onclicklistener event public void ShowMessage (View v) {toast.maketext (mainactivity.this) with XML, " The third method implements the event-bound button ", 1). Show ();}}
The third type of component code in XML:
<button android:id= "@+id/button4" android:layout_width= "wrap_content" android:layout_height= " Wrap_content " android:layout_below=" @id/button3 " android:text=" @string/button4 " android:onclick=" ShowMessage "/>
Android button three ways to implement click events