Android button click event

Source: Internet
Author: User

Method 1: Specify the Click Event function in the XML file

<Button
Android: Id = "@ + ID/button1"
Android: layout_width = "120dip"
Android: layout_height = "wrap_content"
Android: layout_alignparentleft = "true"
Android: layout_below = "@ + ID/textview1"
Android: layout_margintop = "59dp"
  Android: onclick = "onclicklistener"
Android: text = "@ string/mybuttonstr"/>

then implement this function in Code . Note: The function must be public and will not be abnormal.

Public void onclicklistener (view Tager)
{< br> textview textview1 = (textview) findviewbyid (R. id. textview1);
textview1.settext ("Xi'an. wang Lei ");
}

 

Method 2:

Find the button in oncreate of the activity and assign it an event listener. This method is very common.

Public void oncreate (bundle savedinstancestate ){
Super. oncreate (savedinstancestate );
Setcontentview (R. layout. Main );
Button but = (button) This. findviewbyid (Id. button1 );


But. setonclicklistener (New onclicklistener (){

Public void onclick (view v ){
// Todo auto-generated method stub
Log. V ("mytag", "onclick ");
}
});
}

 

Method 3:

This method is actually a variant of method 2. Define an onclicklistener handler in advance, and then use the handler for all the buttons in the activity to judge different IDs for different logic. This method is suitable for many buttons.

Public void oncreate (bundle savedinstancestate ){
Super. oncreate (savedinstancestate );
Setcontentview (R. layout. Main );

View. onclicklistener handler = new onclicklistener (){

@ Override
Public void onclick (view v ){
// Todo auto-generated method stub
Switch (V. GETID ()){
Case ID. button1:
Log. V ("mytag", "button1 onclick ");
Break;
Case ID. button2:
Log. V ("mytag", "button2 onclick ");
Break;
}

}

};

Button btn1 = (button) This. findviewbyid (Id. button1 );
Button btn2 = (button) This. findviewbyid (Id. button2 );

Btn1.setonclicklistener (handler );
Btn2.setonclicklistener (handler );

}

Related Article

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.