The settag (onbect) in the view indicates that an extra data is added to the view. In the future, you can use gettag () to retrieve this data.
You can use multiple buttons to add a listener. Each button has a different settag. The listener uses gettag to identify which button is pressed.
Import Android. App. activity;
Import Android. OS. Bundle;
Import Android. View. view;
Import Android. widget. Button;
Public class main extends Activity {
@ Override
Public void oncreate (bundle savedinstancestate ){
Super. oncreate (savedinstancestate );
Setcontentview (R. layout. Main );
Button button1 = (button) findviewbyid (R. Id. button01 );
Button button2 = (button) findviewbyid (R. Id. button02 );
Button button3 = (button) findviewbyid (R. Id. button03 );
Button button4 = (button) findviewbyid (R. Id. button04 );
Mylistener listener = new mylistener ();
Button1.settag (1 );
Button1.setonclicklistener (listener );
Button2.settag (2 );
Button2.setonclicklistener (listener );
Button3.settag (3 );
Button3.setonclicklistener (listener );
Button4.settag (4 );
Button4.setonclicklistener (listener );
}
Public class mylistener implements view. onclicklistener {
@ Override
Public void onclick (view v ){
Int tag = (integer) v. gettag ();
Switch (TAG ){
Case 1:
System. Out. println ("button1 click ");
Break;
Case 2:
System. Out. println ("button2 click ");
Break;
Case 3:
System. Out. println ("button3 click ");
Break;
Case 4:
System. Out. println ("button4 click ");
Break;
}
}
}
}