【问题标题】:Setting confirmation on button click设置按钮点击确认
【发布时间】:2015-09-28 14:26:30
【问题描述】:

我已经为 android 设计了这个应用程序,用户希望我添加一个确认弹出窗口,以便按钮操作继续。如果单击Yes,则操作会继续,但如果单击No,则过程会中断。我已通读 Web 并看到 dialog 用于此目的。有人可以用示例代码解释它是如何工作的。

【问题讨论】:

    标签: android dialog android-alertdialog


    【解决方案1】:
    new AlertDialog.Builder(this)
        .setTitle("Confirm")
        .setMessage("Do you really want to do Perform this Action?")
        .setIcon(android.R.drawable.ic_dialog_alert)
        .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
    
            public void onClick(DialogInterface dialog, int whichButton) {
                Toast.makeText(MainActivity.this, "yes", Toast.LENGTH_SHORT).show();
            }})
         .setNegativeButton(android.R.string.no,new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog,int id) {
                    // if this button is clicked, just close
                    // the dialog box and do nothing
                    dialog.cancel();
                }
            }).show();
    

    【讨论】:

      【解决方案2】:

      查看下面的示例代码。在此示例中,如果您从活动中调用它,则在 showDialog 上下文参数中传递“this”,如果您在片段中显示该对话框,则传递 getActivity() 而不是上下文

      public void showDialog(Context context,String title,String msg){
      
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
        // set title
        alertDialogBuilder.setTitle(title);
        // set dialog message
        alertDialogBuilder.setMessage(msg).setCancelable(false)
                  .setPositiveButton("Yes",new DialogInterface.OnClickListener() {
                      public void onClick(DialogInterface dialog,int id) {
                          // if this button is clicked, close
                          // current activity
                          MainActivity.this.finish();
                      }
                    })
                  .setNegativeButton("No",new DialogInterface.OnClickListener() {
                      public void onClick(DialogInterface dialog,int id) {
                          // if this button is clicked, just close
                          // the dialog box and do nothing
                          dialog.cancel();
                      }
                  });
      
          // create alert dialog
          AlertDialog alertDialog = alertDialogBuilder.create();
      
          // show it
          alertDialog.show();
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-23
        • 1970-01-01
        • 2011-07-02
        • 2016-05-25
        相关资源
        最近更新 更多