Button Basic Use method
First, add the button control to the XML layout file. can also be added through the program.
Set some properties of the button in the layout file, such as position, width height, word on button, color, etc.
The more important thing is to give the button an ID number, which is the button's only name.
This allows the button to be obtained in the program in the following form:
Button = (button) Findviewbyid (R.id.buttonid);
Handle button click
There are two ways to handle button clicks.
The first is to implement this method in activity by setting the name of the method that handles the Click event through the OnClick property.
Another method is a typical application of the event monitoring mechanism, which is described in detail below.
1. Setting the processing method via the OnClick property
To set the properties of a button in an XML layout file:
android:onclick= "Yourmethodname"
The method is then implemented in the corresponding acitivity of the layout file:
/**/publicvoid yourmethodname (view view ) { // Do something on response to button click }
It is important to note that this method must meet three conditions:
1.public
2. return void
3. There is only one parameter view, this view is the control that is clicked.
2. Adding Listener objects using Setonclicklistener
Can write an internal class , implement the Onclicklistener interface, implement the OnClick method in this class, the method is written in the button click to do the specific work.
The object of this inner class is passed into the Setonclicklistener method of the button, that is, the binding of the Listener object and the button is completed (the event listener is registered on the event Source button), and the OnClick method of the listener object is invoked whenever the button is clicked.
of course, there is no need to write an internal class, such as this example :
Button button = (Button) Findviewbyid (r.id.button_send); Button.setonclicklistener (new View.onclicklistener () { publicvoid OnClick (View v) { // do something in response to button click }});
Basic use of button for Android base control