【问题标题】:OK/Cancel dialog for Back Button返回按钮的确定/取消对话框
【发布时间】:2012-01-10 10:12:20
【问题描述】:

我正在尝试制作一个对话框按钮,当我在主要活动上时会弹出一个对话框按钮,并询问用户是否确定要关闭程序。我不确定在 //Action for the Yes 按钮中添加什么...有没有更好的方法来做到这一点?

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {



    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {  
           AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
            alt_bld.setMessage("Are you sure you want to exit?")
            .setCancelable(false)
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                // Action for 'Yes' Button



                }
            })
            .setNegativeButton("No", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                //  Action for 'NO' Button

                    dialog.cancel();
                }
            });
            AlertDialog alert = alt_bld.create();
            // Title for AlertDialog
            alert.setTitle("Exit Game?");
            // Icon for AlertDialog
            alert.setIcon(R.drawable.icon);
            alert.show();


    return true;
    }

    return super.onKeyDown(keyCode, event);
}

【问题讨论】:

  • 按下 ok 按钮时调用 finish() 可以解决问题
  • 我建议重写 onBackPressed() 函数而不是处理特定的键事件。

标签: android dialog


【解决方案1】:

例如,您可以完成您的Activity。调用finish() 方法。

除此之外,请考虑在Activity 中使用 DialogFragments(如果您使用兼容性库)或showDialog() 方法 - 这将防止窗口泄漏。

【讨论】:

    【解决方案2】:

    你可以在yes按钮的动作中使用简单的finish()语句退出活动

    您也可以为此重写 onBackPressed 方法

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-27
      • 1970-01-01
      • 2011-09-16
      • 1970-01-01
      • 1970-01-01
      • 2017-10-09
      • 2012-05-03
      • 1970-01-01
      相关资源
      最近更新 更多