Four Ways to implement button

Source: Internet
Author: User

/**
* Four Ways to type button
*/

The first gets the button and then adds a listen event to the button, creating a class that implements the Onclicklistener interface.
The response event of a button is implemented in the interface class.
Button callbtn = (button) This.findviewbyid (R.ID.CALLBTN);
Callbtn.setonclicklistener (New MyListener ());

To create a class that implements an interface
public class MyListener implements Onclicklistener {

@Override
public void OnClick (View v) {
/**
* Method implementation
*/
}
}

The second is to create an instance of the interface directly when the listener is added
Button callbtn = (button) This.findviewbyid (R.ID.CALLBTN);
Callbtn.setonclicklistener (New Onclicklistener () {

@Override
public void OnClick (View v) {
/**
* Specific implementation
*/
}
});

The third is to let mainactivity Implement Interface Onclicklistener

public class Mainactivity extends Activity implements Onclicklistener {

@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);

Button callbtn = (button) This.findviewbyid (R.ID.CALLBTN);
Callbtn.setonclicklistener (this);
}

@Override
public void OnClick (View v) {
  

/**
* When there are many buttons, let the current mainactivity inherit the Onclicklistener interface,
In the method to be implemented, the switch case statement is used to determine
*
*/
Switch (V.getid ()) {
Case R.ID.CALLBTN:
Break
Default
Break
}
}

}

}

Fourth add android:onclick= "Callphone" in Activity_main.xml <button/>
and make it in Mainactivity.java.
is actually achieved through reflection.

public class Mainactivity extends Activity {

@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
}
public void callbtnclicked (View v) {
/**
* Specific implementation
*/
}

}

Four Ways to implement button

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.