Sixth lesson for Joshui teacher
One, add a button and bind the event with an external class
XML file: <button android:id= "@+id/button1" android:layout_width= "Wrap_content" android: layout_height= "Wrap_content" android:layout_alignparentleft= "true" android:text= "button 1"/>//Main class: Public Class Mainactivity extends Activity { private Button btn1 = null; @Override protected void onCreate (Bundle savedinstancestate) { super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); BTN1 = (Button) Findviewbyid (r.id.button1); Btn1.setonclicklistener (New ButtonClick ()); Method One, define the outer class to bind the event class ButtonClick implements Onclicklistener {public void OnClick (View arg0) {System.out.printline (" Clicked Button1 "); }
Two, binding an event with an inner class
<span style= "Color:rgb (51, 51, 51); >btn1.setonclicklistener (New Onclicklistener () { ///Method Two, definition </span><span style= "color: #ff0000;" ><strong> internal class </strong></span><span style= "Color:rgb (51, 51, 51); > Bind event @overridepublic void OnClick (View arg0) {//Toast to display hints </span><span style= "color: #ff0000;" ><strong>//Note: Toast.maketext (context context, charsequence text, int duration) </strong></span> <span style= "Color:rgb (51, 51, 51); ></span><span style= "color: #ff0000;" ><strong>//context to point to the main class himself, this to figure out!!!!, text setting, duration setting time </strong></span><span style= " Color: #333333; " >toast.maketext (Getapplicationcontext (), "click!", Toast.length_long). Show ();}); </span>
three, with multiple buttons, set the inner class as a variable to make the code more friendly
The XML file doesn't say much,
<span style= "color: #333333;" >private button btn1 = null;private button btn2 = null; BTN1 = (Button) Findviewbyid (r.id.button1); BTN2 = (Button) Findviewbyid (r.id.button2); Btn1.setonclicklistener (listener); There are multiple button Btn2.setonclicklistener (listener); private Onclicklistener listener =new Onclicklistener () { // Define a variable to install this inner class @overridepublic void OnClick (View v) {</span><span style= "color: #ff0000;" ><strong>//Note what the view is, and then why is it forced to convert to button!! </strong></span><span style= "color: #333333;" >button btn = (Button) v;switch (Btn.getid ()) {Case R.id.button1:toast.maketext (Getapplicationcontext (), "click1!", Toast.length_long). Show (); Break;case R.id.button2:toast.maketext (Getapplicationcontext (), "click2!", Toast.LENGTH _long). Show (); break;}}; </span>
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Android Learning Note (3) button control learning