一个简单讲述对话框的Android实例,剖析其中的原理,下文直接是代码。
***步:先配置项目中的res文件夹中values/strings.xml
Java代码:
- <?xml version="1.0" encoding="utf-8"?>
- <resources>
- <string name="app_name">普通对话框</string>
- <string name="button">显示普通对话框</string>
- <string name="title">普通对话框</string>
- <string name="ok">确定</string>
- <string name="message">这是一个普通对话框</string>
- </resources>
第二步:配置项目中的res文件夹中layout/main.xml 用来创建输入框和“显示普通对话框”按钮
java代码:
- <?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="wrap_content"
- >
- <EditText android:id="@+id/editText"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/message"/>
- <Button android:id="@+id/button"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/button"/>
- </LinearLayout>
第三步:编写src文件夹包底下的.java文件
java代码:
- package eoe.demo;
- import android.app.Activity;
- import android.app.AlertDialog;
- import android.app.AlertDialog.Builder;
- import android.app.Dialog;
- import android.content.DialogInterface;
- import android.os.Bundle;
- import android.util.Log;
- import android.view.View;
- import android.widget.Button;
- import android.widget.EditText;
- public class CommonDialogActivity extends Activity {
- protected static final int COMMON_DIALOG = 1;
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- Button button= (Button)findViewById(R.id.button);
- View.OnClickListener listener = new View.OnClickListener() {
- public void onClick(View arg0) {
- // TODO Auto-generated method stub
- showDialog(COMMON_DIALOG);
- }
- };
- button.setOnClickListener(listener);
- }
- /*
- * 使用onCreateDialog(int)来管理对话框的状态,
- * 那么每次对话框被解除时,
- * 该对话框对象的状态会被Activity保存. 调用
- * removeDialog(int)将所有该对象的内部引用
- * 移除 如本程序那样,如果不加removeDialog,
- * 那么显示的是***次的内容
- */
- protected Dialog onCreateDialog(int id){
- AlertDialog dialog=null;
- EditText editText = (EditText) findViewById(R.id.editText);
- switch(id){
- case COMMON_DIALOG:
- Builder builder = new AlertDialog.Builder(this);
- builder.setIcon(R.drawable.icon);
- builder.setMessage(editText.getText());
- builder.setTitle(R.string.title);
- DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface arg0, int arg1) {
- // TODO Auto-generated method stub
- removeDialog(COMMON_DIALOG);
- }
- };
- builder.setPositiveButton(R.string.ok, listener);
- dialog = builder.create();
- break;
- default:
- break;
- }
- Log.e("onCreateDialog", "onCreateDialog");
- return dialog;
- }
- }
【编辑推荐】