String.xml文件的代码如下:
1 <resources> 2 <string name="app_name">普通对话框案例</string> 3 <string name="btn">显示普通对话框</string> 4 <string name="title">普通对话框</string> 5 <string name="ok">确定</string> 6 <string name="dialog_msg">这是普通对话框中的内容!!!</string> 7 </resources>
activity_common_dialog代码如下:
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout 3 xmlns:android="http://schemas.android.com/apk/res/android" 4 android:orientation="vertical" 5 android:layout_width="fill_parent" 6 android:layout_height="fill_parent"> 7 8 <EditText 9 android:text="" 10 android:id="@+id/EidtText01" 11 android:cursorVisible="false" 12 android:layout_width="fill_parent" 13 android:layout_height="wrap_content" /> 14 15 <Button 16 android:id="@+id/Button01" 17 android:text="@string/btn" 18 android:layout_width="fill_parent" 19 android:layout_height="wrap_content" /> 20 21 </LinearLayout>
java文件代码如下:
1 package com.example.sample_6_3; 2 3 import android.app.Dialog; 4 import android.content.DialogInterface; 5 import android.support.v7.app.AlertDialog; 6 import android.support.v7.app.AppCompatActivity; 7 import android.os.Bundle; 8 import android.view.View; 9 import android.widget.Button; 10 import android.widget.EditText; 11 12 public class CommonDialogActivity extends AppCompatActivity { 13 final int COMMON_DIALOG = 1; 14 @Override 15 protected void onCreate(Bundle savedInstanceState) { 16 super.onCreate(savedInstanceState); 17 setContentView(R.layout.activity_common_dialog); 18 Button btn = (Button) findViewById(R.id.Button01); 19 btn.setOnClickListener(new View.OnClickListener() { 20 @Override 21 public void onClick(View v) { 22 showDialog(COMMON_DIALOG); //显示普通对话框 23 } 24 }); 25 } 26 protected Dialog onCreateDialog(int id) { 27 Dialog dialog = null; //声明一个dialog对象用于返回 28 switch (id) { //对id进行判断 29 case COMMON_DIALOG: 30 AlertDialog.Builder b = new AlertDialog.Builder(this); 31 b.setIcon(R.drawable.dialog); //设置对话框图标 32 b.setTitle(R.string.title); //设置对话框标题 33 b.setMessage(R.string.dialog_msg); //设置对话框显示内容 34 b.setPositiveButton( 35 R.string.ok, 36 new DialogInterface.OnClickListener() { 37 @Override 38 public void onClick(DialogInterface dialog, int which) { 39 EditText et = (EditText) findViewById(R.id.EidtText01); 40 et.setText(R.string.dialog_msg); //设置EditText内容 41 } 42 }); 43 dialog = b.create(); //生成dialog对象 44 break; 45 default: 46 break; 47 } 48 return dialog; //返回生产dialog的对象 49 } 50 }