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 );
}