Hello everyone, in this section, we will combine the simple button Event Response to display the application of the toast control. In the previous section, we have learned. the button object is defined in XML. Today we will learn how to implement event response for the button,
The event processing triggered by the button is called event handle, but in Android, the button event is controlled by the system's button. onclicklistener and is familiar with Java.ProgramThe readers of the design should be familiar with onxxxlistener. The following demo will show the textview text changed when the button is clicked, And a toast reminder will appear on the screen for a period of time.
Let's take a look:
Before clicking the button:
Click the button:
We mainly changed two places in the program.Main. xmlThe other isButtondemo. Java
Main. xml CodeAs follows::
// After 1.5, the default linearlayout layout
Android: orientation = "vertical"
Android: layout_width = "fill_parent"
Android: layout_height = "fill_parent"
Android: id = "@ + ID/textview1" // define the ID so that the Java class can locate it and control it.
Android: layout_width = "fill_parent"
Android: layout_height = "wrap_content"
Android: TEXT = "@ string/Hello"
/>
Android: id = "@ + ID/button1"
Android: layout_width = "60px"
Android: layout_height = "wrap_content"
Android: layout_gravity = "right"// Place the button on the right
Android: text = "OK"
/>
</Linearlayout>
Button. JavaThe Code is as follows:
Package com. Android. test;
Import Android. App. activity;
Import Android. OS. Bundle;
Import Android. View. view;
Import Android. widget. Button;
Import Android. widget. textview;
Import Android. widget. Toast;
Public class buttondemo extends activity {
Private textview textview1;
Private button button1;
Public void oncreate (bundle savedinstancestate ){
Super. oncreate (savedinstancestate );
Setcontentview (R. layout. Main );
// Locate the textview and button controls defined in Main. xml by ID
Textview1 = (textview) findviewbyid (R. Id. textview1 );
Button1 = (button) findviewbyid (R. Id. button1 );
// Add Event Response
Button1.setonclicklistener (New button. onclicklistener (){
Public void onclick (view V)
{
// Toast prompt control
Toast. maketext (buttondemo. This,
"The text in textview has changed. Have you noticed it? ",
Toast. length_long). Show ();
// Change the textview text
Textview1.settext ("Welcome to Wei zhulin's blog! ");
}
});
}
}