I have always wanted to write something, but I don't know what to write. I have been learning Android development. I just took this opportunity to practice writing. Well, let's say, today I want to learn about the Android Button control and TextView control. What ?? Do you still have to build an Android development platform? Please go to Baidu or Google.
The Button control has event listening. If you want to handle click events, you need to register a listener for the Button control. Now, let's take a look at today's code, first of all main. xml.
<? Xml version = "1.0" encoding = "UTF-8"?>
<LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android"
Android: orientation = "vertical" android: layout_width = "fill_parent"
Android: layout_height = "fill_parent">
<TextView android: id = "@ + id/text" android: layout_width = "fill_parent"
Android: layout_height = "wrap_content" android: text = "@ string/hello"/>
<Button android: layout_width = "match_parent"
Android: layout_height = "wrap_content" android: text = "button" android: id = "@ + id/Button"> </button>
</LinearLayout>
A Button control is added and an id (android: id = "@ + id/button") is set for it. What? Why do I need to set the ID? This is to facilitate the discovery of the control in main. xml in the Activity and create events or processes for the corresponding control. You don't want to click the control when there is nothing at all, right? Now let's take a look at the code in the Activity:
Import java. util. Date;
Import android. app. Activity;
Import android. OS. Bundle;
Import android. view. View;
Import android. view. View. OnClickListener;
Import android. widget. Button;
Import android. widget. TextView;
Public class ButtonDemoActivity extends Activity implements OnClickListener
{
Private TextView text = null;
/** Called when the activity is first created .*/
@ Override
Public void onCreate (Bundle savedInstanceState)
{
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );
// Find the TextView control in main. xml by ID
Text = (TextView) findViewById (R. id. text );
// Find the Button control in main. xml by ID
Button button = (Button) findViewById (R. id. button );
// Add a click listener for the Button control
Button. setOnClickListener (this );
}
/**
* Click to listen to all the controls in main. xml. Of course, you must register the listener for the control. Example: button. setOnClickListener (this );
*/
@ Override
Public void onClick (View v)
{
UpdateTime ();
}
Private void updateTime ()
{
// Set the text in the text Control
Text. setText (new Date (). toString ());
}
}
OK. After the code is written, let the simulator run it. Click each button to see if the TextView above has changed? Is it easy? From today on, we have officially learned about Android development.
From: kangkangz4 Column