【问题标题】:Show confirmation dialog in Fragment在 Fragment 中显示确认对话框
【发布时间】:2012-03-18 21:37:15
【问题描述】:

我正在将我的 Android 应用程序转换为使用片段。以前,我有一个活动,现在是一个片段。因此,此代码不能再使用:

showDialog(CONFIRM_ID);
// ...
@Override
public Dialog onCreateDialog(int id) {
    // Create the confirmation dialog...
}

Fragment 对象中,我需要显示一个确认对话框,确认后我会返回对象进行状态更新。

例如

  1. 片段 X 内部。
  2. 显示确认对话框。
  3. 如果“是”,则更新 X 的 UI。

我怎样才能做到这一点?请提供工作示例代码。

【问题讨论】:

    标签: android android-fragments android-fragmentactivity


    【解决方案1】:

    您可以使用此处显示的代码简单地创建对话框 (AlertDialog):http://developer.android.com/guide/topics/ui/dialogs.html#AlertDialog

    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) {
                    MyActivity.this.finish();
               }
           })
           .setNegativeButton("No", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
               }
           });
    AlertDialog alert = builder.create();
    alert.show();
    

    如果您需要使用不会立即关闭对话框本身的按钮创建对话框,您可以在此处查看我的答案:How to prevent a dialog from closing when a button is clicked

    【讨论】:

    • 谢谢。这就足够了! (但我怀疑最好的解决方案是使用DialogFragment 并以某种方式将结果传播回原始片段。)
    【解决方案2】:
             AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());       
             builder.setTitle("Your Title");
             builder.setMessage("Your Dialog Message");
             builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                 public void onClick(DialogInterface dialog, int id) {
                      //TODO
                      dialog.dismiss();
                 }
             });
             builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                 public void onClick(DialogInterface dialog, int id) {
                      //TODO
                      dialog.dismiss();
                 }
             });
             AlertDialog dialog = builder.create();
             dialog.show();
    

    【讨论】:

      猜你喜欢
      • 2021-06-28
      • 1970-01-01
      • 2016-10-08
      • 2015-12-20
      • 2016-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多