The Android control onclick event can be implemented in one of three ways:
1. Implement the OnClick method
Specifies the OnClick method in the XML of layout, which is implemented in activity. Typically used for button.
file:res/layout/activity_main.xml << /span>button = "@+id/mybutton" Android:layout_width = "Wrap_content" Android:layout_height = "Wrap_content" Android:onclick = "Btnclick" />
file:java/com/xxx/proj/Mainactivity.java publicvoid Btnclick (view view) { New Intent (mainactivity. this, main2activity. class ); Intent.putextra ("Extra_data", "New Activy"); StartActivity (intent); }
2. Binding methods for controls in OnCreate
If the OnClick method is specified at the same time in the XML of layout, the method in XML is executed first
file:java/com/xxx/proj/Mainactivity.javaprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); Button Button=(Button) Findviewbyid (R.id.mybutton); Button.settext (R.string.button_text); Button.setonclicklistener ( This); Button.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View v) {Intent Intent=NewIntent (mainactivity. This, Main2activity.class); Intent.putextra ("Extra_data", "New Activity"); StartActivity (Intent); } }); }
3. Implement the Onclicklistener interface
This method overwrite the OnClick method in Onclicklistener to respond to the respective events with different controls, and the advantage is to solve all the onclick problems in the activity.
file:java/com/xxx/proj/Mainactivity.java Public classMainactivityextendsAppcompatactivityImplementsView.onclicklistener {PrivateButton Button =NULL; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); Button=(Button) Findviewbyid (R.id.mybutton); Button.settext (R.string.button_text); Button.setonclicklistener ( This); } @Override Public voidOnClick (View v) {if(v = =button) {Intent Intent=NewIntent (mainactivity. This, Main2activity.class); Intent.putextra ("Extra_data", "New Activity"); StartActivity (Intent); } }}
Reference:
Three ways to realize the Onclicklistener of <button >
<How to implement button click events and listeners for Android >
Android Control onclick Event