In Android development, the operation of the control is the most basic technology, especially the button click action. I have summarized the following 4 kinds of button click implementation Method. To share with you, I hope you will criticize correct.
(1) Anonymous inner class implementation
This approach is the simplest implementation, it is generally just beginning to learn Android or learning based on user interface development, this method is required to learn. The implementation code is as follows:
public class Mainactivity extends Activity { private button button; @Override protected void onCreate (Bundle savedinstancestate) { super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); Button = (button) Findviewbyid (R.ID.ID_BTN); Button.setonclicklistener (New View.onclicklistener () { @Override public void OnClick (View v) { Toast.maketext (mainactivity.this, "button clicked", Toast.length_long). Show ();}} );} }
(2) Activity Implementation Onclicklistener interface
Using this method is to implements View.onclicklistener in the current activity. Then implement the methods that are not implemented in the interface. Specific to the operation of the button or business logic in the onclick () implementation, the implementation code is as follows:
public class Mainactivity extends Activity implements View.onclicklistener { private button button; @Override protected void onCreate (Bundle savedinstancestate) { super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); Button = (button) Findviewbyid (R.ID.ID_BTN); Button.setonclicklistener (this); } @Override public void OnClick (View v) { switch (V.getid ()) { r.id.id_btn: toast.maketext ( Mainactivity.this, "button was clicked", Toast.length_long). Show (); break; Default: Break;}}}
(3) Inner class implements Onclicklistener interface
The method is to create an inner class in the current activity main class that implements Onclicklistener. Ideas with method two. The implementation code is as follows:
public class Mainactivity extends Activity { private button button; @Override protected void onCreate (Bundle savedinstancestate) { super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); Button = (button) Findviewbyid (R.ID.ID_BTN); Myclick Myclick = new Myclick (); Button.setonclicklistener (Myclick); } Class Myclick implements View.onclicklistener { @Override public void OnClick (View v) { switch (V.getid ( ) {case r.id.id_btn: toast.maketext (mainactivity.this, "button was clicked", Toast.length_long). Show (); Break;}}}}
(4) Annotation method: Refer to my other blog (using Butterknife annotation Framework to achieve view click action): http://blog.csdn.net/chenyufeng1991/article/details/46901101
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
4 Ways to implement button clicks in Android