How to add a view's Setonclicklistener

Source: Internet
Author: User

1) The first, but also the longest-to-see method of addition (click on the button for example)

1 Button btn = (button) Findviewbyid (R.id.mybutton);
2 btn. Setonclicklistener (New View.onclicklistener () {
3 Public void OnClick (View v) {
4//do Something
5 }
6 });



2) Second, the following method is slightly simpler than the previous one, allowing multiple buttons to share a single listener. To control the response to different button click events via the switch:

1 Button btn = (button) Findviewbyid (R.id.mybutton);
2 Button btn2 = (button) Findviewbyid (R.id.mybutton2);
3 Btn.setonclicklistener (handler);
4 Btn2.setonclicklistener (handler);
5 View.onclicklistener handler = View.onclicklistener () {
6 Public void OnClick (View v) {
7 switch (V.getid ()) {
8
9//do Something
Ten break ;
11
//do something
Break ;
+ }
}




3) Third, directly clicklistener bundle the views element in the XML layout, the listener method defined in the program requires a parameter with a view type:

1 <?xml version= "1.0" encoding= "Utf-8"?>
2 <linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"
3 android:orientation= "vertical" android:layout_width= "fill_parent"
4 android:layout_height= "Fill_parent" >
5 <textview android:layout_width= "Fill_parent"
6 android:layout_height= "wrap_content" android:id= "@+id/text"
7 android:text= "@string/hello"/>
8 <button android:id= "@+id/mybutton" android:layout_height= "Wrap_content"
9 android:layout_width= "wrap_content" android:onclick= "Mybuttonlistener" ></Button>
Ten </LinearLayout>

Java code:

1 Button btn = (button) Findviewbyid (R.id.mybutton);

3 public void Mybuttonlistener (View target) {
4//do Something
5 }

How to add a view's Setonclicklistener

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.