The button is an important control that the program uses to interact with the user, and I believe you are already familiar with the control because we used the button too many times in the previous chapter. Its configurable properties and TextView are similar, and we can add buttons like this in Activity_main.xml:
<linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android" android:layout_width= "match_parent" android:layout_height= "Match_parent "
android:orientation= "Vertical" >
...
<button android:id= "@+id/button" android:layout_width= "match_parent" android:layout_height= "Wrap_content" android:text= "button"/>
</LinearLayout>
Interface 3.4 After adding the Button is shown.
Figure 3.4
Then we can register a listener for the button's click event in Mainactivity, as follows:
public class Mainactivity extends Activity {
Private button button;
@Override
Protected voidoncreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main);
Button = (button) Findviewbyid (R.id.button);
Button.setonclicklistener (New Onclicklistener () {
@Override
public void OnClick (View v) {
// add logic here
}
});
}
}
This will execute the OnClick () method in the listener whenever the button is clicked, and we just need to add the pending logic to this method. If you don't like using anonymous classes to register listeners, you can also register using the implementation interface, as shown in the following code:
public class Mainactivity extends Activity implementsonclicklistener {
Private button button;
@Override
Protected voidoncreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main);
Button = (button) Findviewbyid (R.id.button);
Button.setonclicklistener (this);
}
@Override
public void OnClick (View v) {
Switch (V.getid ()) {
Case R.id.button:
// add logic here
Break
Default
Break
}
}
}
Both of these can be used to monitor the button click events, and the use of which is entirely your preference.
Android:button controls