代码改变世界

Android系列之LinearLayout+EditText+Button+AlertDialog

2010-08-12 14:11  $等待$  阅读(2976)  评论(1编辑  收藏  举报

这个简单的例子是EditText中默认有个字符串text,单击Show按钮,弹出AlertDialog显示EditText中的内容,单击Clear按钮,清除EditText中的内容!!

Activity用到两个LinearLayout,两个Button,一个TextView,一个EditText!

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:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
<EditText
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/text"
    android:id="@+id/text"
    />
<LinearLayout
	android:id="@+id/linearlayout1"
	android:layout_width="fill_parent"
	android:layout_height="wrap_content"
	android:gravity="center"
	>
	<Button
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:text="@string/btnShow"
		android:id="@+id/btnShow"
		/>
	<Button
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:text="@string/btnClear"
		android:id="@+id/btnClear"
		/>
</LinearLayout>
</LinearLayout>

 

java代码

 

1 import android.app.Activity;
2  import android.app.AlertDialog;
3  import android.os.Bundle;
4  import android.view.View;
5 import android.widget.Button;
6 import android.widget.EditText;
7
8 public class practice extends Activity {
9 Button btnShow;
10 Button btnClear;
11 EditText text;
12 /** Called when the activity is first created. */
13 @Override
14 public void onCreate(Bundle savedInstanceState) {
15 super.onCreate(savedInstanceState);
16 setContentView(R.layout.main);
17
18 btnShow = (Button)findViewById(R.id.btnShow);
19 btnClear = (Button)findViewById(R.id.btnClear);
20 text = (EditText)findViewById(R.id.text);
21
22 btnShow.setOnClickListener(new View.OnClickListener() {
23
24 @Override
25 public void onClick(View v) {
26 // TODO Auto-generated method stub
27 new AlertDialog.Builder(practice.this)
28 .setTitle("Infomation")
29 .setIcon(android.R.drawable.ic_dialog_dialer)
30 .setMessage(text.getText())
31 .show();
32 }
33 });
34
35 btnClear.setOnClickListener(new View.OnClickListener() {
36
37 @Override
38 public void onClick(View v) {
39 // TODO Auto-generated method stub
40 text.setText("");
41 }
42 });
43 }
44 }