I. Overview
A button, as its name implies, is a button. Its main function is to respond to the actions when a user presses a button.
II. Application
Create a new project named mybutton and add the following content to the/RES/layout/Main. xml file:
1 <Button
2 android:id="@+id/button"
3 android:layout_width="fill_parent"
4 android:layout_height="wrap_content"
5 android:text="Click"
6 />
The content of the added main. xml file is:
1 <?xml version="1.0" encoding="utf-8"?>
2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3 android:layout_width="fill_parent"
4 android:layout_height="fill_parent"
5 android:orientation="vertical" >
6
7 <TextView
8 android:layout_width="fill_parent"
9 android:layout_height="wrap_content"
10 android:text="@string/hello" />
11
12 <Button
13 android:id="@+id/button"
14 android:layout_width="fill_parent"
15 android:layout_height="wrap_content"
16 android:text="Click"
17 />
18
19 </LinearLayout>
Modify the mybuttonactivity. Java file and declare a button object mbutton in the mybuttonactivity class.
private Button mButton = null;
Use the findviewbyid () function in the oncreate () function to instantiate mbutton.
mButton = (Button)findViewById(R.id.button);
Then write the mbutton listening function.
mButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
PlayToast("You Clicked Button");
}
});
The playtoast () function uses the toast class to display the string "you clicked button", which is relatively simple, as shown below:
private void PlayToast(String s)
{
Toast toast = Toast.makeText(this, s , Toast.LENGTH_LONG);
toast.show();
}
Okay. The following is the complete content of the mybuttonactivity. Java file:
1 package com.nan.button;
2
3 import android.app.Activity;
4 import android.os.Bundle;
5 import android.view.View;
6 import android.widget.Button;
7 import android.widget.Toast;
8
9
10
11 public class MyButtonActivity extends Activity
12 {
13 private Button mButton = null;
14
15
16 /** Called when the activity is first created. */
17 @Override
18 public void onCreate(Bundle savedInstanceState)
19 {
20 super.onCreate(savedInstanceState);
21 setContentView(R.layout.main);
22
23 mButton = (Button)findViewById(R.id.button);
24 mButton.setOnClickListener(new View.OnClickListener()
25 {
26
27 @Override
28 public void onClick(View v)
29 {
30 // TODO Auto-generated method stub
31 PlayToast("You Clicked Button");
32 }
33 });
34
35 }
36
37
38 private void PlayToast(String s)
39 {
40 Toast toast = Toast.makeText(this, s , Toast.LENGTH_LONG);
41 toast.show();
42 }
43
44 }
Run the program and click the button. The effect is as follows: