1. Define the inner class, implement the Click event, use the inner class object to pass in the Setonclicklistener () method of the event source
Private class Implements view.onclicklistener{ @Override publicvoid OnClick (View v) { // function Code } }
2. Using anonymous inner classes to implement click events
Setonclicklistener (new View.onclicklistener () { @Override publicvoid OnClick (View v) { // function code } });
3. In the Bind-point-click event, the current Activity object is passed in, Setonclicklistener (this), which represents a reference to the activity object in which the current control is located, using this method, The current activity is required to implement the View.onclicklistener interface, in which the OnClick method determines what action to take by judging the ID of the event source (control).
public class mainactivity extends actionbaractivity Onclicklistener {@Override protected void OnCreate (Bundle savedinstancestate) { super .oncreate (Savedinstancestate); Setcontentview (R.layout.activity_main); button But = (button) this .findviewbyid ( r.id.bt_dial);
But.setonclicklistener (this); } @Override publicvoid OnClick (View v) { switch (V.getid ()) { case r.id.but: // function code break ; default: break; }}}
4. In the activity layout file, bind the onclick event to the event source and provide an implementation of the event in the activity
Activity_xxx_xml, add android:onclick= "buttonclicked", where buttonclicked is the implementation of the Click event
< Button Android:onclick = "ButtonClicked" android:id= "@+id/butl" android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" android:text= "button" />
Activity.java file, add the following code, note that the access to the Click event must be public, and the parameter is the view type
Public void buttonclicked (View v) { if(v.getid () = =r.id.but) {// function code } }
Android Basics-Four ways to click events