When you get some controls (such as a button) in Android, you typically add a click event to it, and the click events in Android are written in a total of 4.
Assume that the following is declared in the layout file
....... < Button Android:layout_width = "Match_parent" Android:layout_height = "Wrap_content" Android:id = "@+id/bt_1" /> .......
First, through anonymous internal class
The main Java code is as follows and gets to the button control first.
Private Button bt_1; @Override protectedvoid onCreate (Bundle savedinstancestate) { super . OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); = (Button) Findviewbyid (r.id.bt_1); Bt_1.setonclicklistener (new Onclicklistener () { @Override public void OnClick (View v) { // Click to trigger execution of code }
Second, through the internal class
First get to the control and create an inner class that implements the Onclicklistener interface.
PrivateButton bt_1; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); Bt_1=(Button) Findviewbyid (r.id.bt_1); Bt_1.setonclicklistener (NewMyListener ()); } classMyListenerImplementsonclicklistener{@Override Public voidOnClick (View v) {//code that triggers execution when a button is clicked } }
Third, add the OnClick property in the layout file
Change the properties of a button in a layout file
< Button Android:layout_width = "Match_parent" android:layout_height= "Wrap_content" android:id= "@+id/bt_1" android:onclick= "click" />
When adding a click event, declare a method directly without having to get to the control
// private Button bt_1; @Override protectedvoid onCreate (Bundle savedinstancestate) { Super . OnCreate (savedinstancestate); Setcontentview (r.layout.activity_main); // bt_1 = (Button) Findviewbyid (r.id.bt_1); } publicvoid Click (View view) { // Code to trigger execution after clicking the button }
Iv. through the implementation of the interface
With this method, the main method implements the Onclicklistener interface, and the OnClick method defined in the interface is overwrite
Public classMainactivityextendsActivityImplementsOnclicklistener {PrivateButton bt_1; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); Bt_1=(Button) Findviewbyid (r.id.bt_1); //This can be passed hereBt_1.setonclicklistener ( This); } @Override Public voidOnClick (View v) {//code to execute after clicking the button }}
4 ways to read and click events in Android