More stay tuned to: http://drovik.com
To add a listener to Android, follow these steps:
1. Define the button in layout and specify the listener of the response.
<? XML version = "1.0" encoding = "UTF-8"?>
<Linearlayout xmlns: Android = "<a href =" http://schemas.android.com/apk/res/android "> http://schemas.android.com/apk/res/android" </a>
Android: Orientation = "vertical"
Android: layout_width = "fill_parent"
Android: layout_height = "fill_parent"
>
<Textview
Android: layout_width = "fill_parent"
Android: layout_height = "wrap_content"
Android: text = "@ string/hello"
/>
<Button
Android: text = "button01"
Android: Id = "@ + ID/button01"
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: onclick = "myclickh1"
/>
<Button
Android: text = "button02"
Android: Id = "@ + ID/button02"
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: onclick = "myclick2"
/>
<Textview
Android: layout_width = "fill_parent"
Android: layout_height = "wrap_content"
Android: text = "@ string/hello"
/>
</Linearlayout>
The following two lines are new features:
Android: onclick = "myclick1"
Android: onclick = "myclick2"
2. Define the public methods myclick1 and myclick2 in the activity.
Import Android. App. activity;
Import Android. OS. Bundle;
Import Android. View. view;
Public class testonclicklistener extends activity {
@ Override
Public void oncreate (bundle savedinstancestate ){
Super. oncreate (savedinstancestate );
Setcontentview (R. layout. Main );
}
Public void myclickhandler01 (view v ){
Settitle ("myclick1 ");
}
Public void myclick2 (view v ){
Settitle ("myclick2 ");
}
}
Import Android. App. activity;
Import Android. OS. Bundle;
Import Android. View. view;
Public class testonclicklistener extends activity {
@ Override
Public void oncreate (bundle savedinstancestate ){
Super. oncreate (savedinstancestate );
Setcontentview (R. layout. Main );
}
Public void myclick1 (view v ){
Settitle ("myclick1 ");
}
Public void myclick2 (view v ){
Settitle ("myclick2 ");
}
}
You can also set the two buttons to the same listener Code as follows:
Android: onclick = "onclick"
Android: onclick = "onclick"
Import Android. App. activity;
Import Android. OS. Bundle;
Import Android. View. view;
Public class testonclicklistener extends activity {
@ Override
Public void oncreate (bundle savedinstancestate ){
Super. oncreate (savedinstancestate );
Setcontentview (R. layout. Main );
}
Public void myclickhandler (view v ){
Switch (V. GETID ()){
Case R. Id. button01:
Settitle ("click1 ");
Break;
Case R. Id. button2:
Settitle ("click2 ");
Break;
}
}
}