Dialog基础(在一个Activity中创建多个Dialog)

本文介绍如何在Android应用中通过重写Activity.onCreateDialog()方法来统一管理多种类型的Dialog,包括创建简单对话框、列表对话框、单选对话框及多选对话框。

 

Android Dev-Guide 推荐重写Activity.onCreateDialog()方法来创建Dialog,这样Dialog就归属于这个Activity了。使用方法是这样的,Activity.showDialog()激发Activity.onCreateDialog()创建Dialog,然后显示之,便于多个Dialog的统一管理。注意,以后再用Activity.showDialog()显示同一个Dialog时,则不会调用Activity.onCreateDialog(),而是调用Activity.onPrepareDialog(),使用上一次显示Dialog时的状态。即 
    第一次:showDialog() -> onCreatedialog() 
    以后: showDialog() -> onPrepareDialog() 

 

        在示例代码中,分别用createExitDialog(),createListDialog(),createRadioDialog(),createCheckboxDialog(),创建4种Dialog,并在Activity中显示。示例代码如下:

public class ShowDialogActivity extends Activity {
    /** Called when the activity is first created. */
public static final String TAG = "ShowDialog";
public static final int ID_EXIT_DIALOG = 1;
public static final int ID_LIST_DIALOG = 2;
public static final int ID_RADIO_DIALOG = 3;
public static final int ID_CHECKBOX_DIALOG = 4;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        showDialog(ID_EXIT_DIALOG);
        showDialog(ID_LIST_DIALOG);
        showDialog(ID_RADIO_DIALOG);
        showDialog(ID_CHECKBOX_DIALOG);
    }  
    @Override
    protected Dialog onCreateDialog(int id) {
    // TODO Auto-generated method stub
    Dialog dialog = null;
    switch(id) {
    case ID_EXIT_DIALOG :
    dialog = createExitDialog();
    break;
    case ID_LIST_DIALOG :
    dialog = createListDialog();
    break;
    case ID_RADIO_DIALOG :
    dialog = createRadioDialog();
    break;
    case ID_CHECKBOX_DIALOG :
    dialog = createCheckboxDialog();
    break;
    default :
    break; }
    if (dialog != null) {
    Log.i(TAG, dialog.toString());
    } else {
    Log.i(TAG, "dialog = null");   }
    return dialog;    }    
    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {
    // TODO Auto-generated method stub
    super.onPrepareDialog(id, dialog);
    }
    //创建简单Dialog
    public Dialog createExitDialog() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Are you sure you want to exit?")
          .setCancelable(false)
          .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int id) {
                   ShowDialogActivity.this.finish();
              }
          })
          .setNegativeButton("No", new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int id) {
                   dialog.cancel();
              }
          });
    return builder.create();
    }
    //创建ListDialog
    public Dialog createListDialog() {
    final CharSequence[] items = {"Red", "Green", "Blue"};
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Pick a color");
    builder.setItems(items, new DialogInterface.OnClickListener() {
       public void onClick(DialogInterface dialog, int item) {
           Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
       }
    });
    return builder.create();
    }
    //创建单选Dialog
    public Dialog createRadioDialog() {
    final CharSequence[] items = {"Red", "Green", "Blue"};
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Pick a color");
    builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
       public void onClick(DialogInterface dialog, int position) {
           Toast.makeText(getApplicationContext(), position + " -> " + items[position], Toast.LENGTH_SHORT).show();
           dialog.dismiss();
       }
    });
    return builder.create();
    }
    //创建多选Dialog
    public Dialog createCheckboxDialog() {
    final CharSequence[] items = {"Red", "Green", "Blue"};
    final boolean [] checked = new boolean [] {false, false, false};
   
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Pick a color");
    builder.setMultiChoiceItems(items, checked, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
// TODO Auto-generated method stub
}
});
    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int id) {
               ShowDialogActivity.this.finish();
          }
      })
      .setNegativeButton("取消", new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int id) {
               dialog.cancel();
          }
      });
    return builder.create();
    }
}

 

Android 开发中,`Dialog` 并不是一个独立的 `Activity`。`Dialog` 是一种轻量级的用户界面组件,通常依附于当前的 `Activity`,用于在当前界面中弹出一个对话框,以实现用户交互[^4]。它不具备 `Activity` 的生命周期,也不拥有独立的任务栈。 `Dialog` 的生命周期完全依赖于其所属的 `Activity`。当 `Activity` 被销毁时,所有依附于该 `Activity` 的 `Dialog` 实例也会被销毁。因此,`Dialog` 不能像 `Activity` 那样独立运行或被系统单独管理[^1]。 虽然有些开发者会通过设置特定的主题(如 `Theme.Dialog`)让某个 `Activity` 表现得像一个对话框,但这种方式本质上仍然是一个 `Activity`,与标准的 `Dialog` 控件在实现机制和使用场景上存在本质区别[^3]。 ### 使用 Dialog 的优势 - **轻量级**:`Dialog` 的资源消耗比 `Activity` 小,适合简单的交互。 - **生命周期简单**:无需处理复杂的生命周期变化,只需关注显示与隐藏。 - **集成度高**:可以更方便地与当前 `Activity` 数据交互,避免跨 `Activity` 通信的问题。 ### 使用 Activity 模拟 Dialog 的场景 尽管 `Dialog` 有诸多优点,但在某些复杂场景下,例如需要更复杂的 UI 控制、涉及较多的业务逻辑或需要更好的内存管理时,开发者可能会选择使用 `Activity` 来模拟 `Dialog` 的行为。这种做法虽然牺牲了轻量级的优势,但可以获得更高的灵活性和可维护性[^1]。 ```xml <!-- 示例:在 AndroidManifest.xml 中配置一个 Dialog 风格的 Activity --> <activity android:name=".MyDialogActivity" android:theme="@style/Theme.AppCompat.Light.Dialog" /> ``` ### 总结 `Dialog` 并不是一个 `Activity`,而是一个依附于当前 `Activity` 的 UI 组件。开发者可以根据实际需求选择使用 `Dialog` 或者使用 `Activity` 模拟对话框效果。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值