用户单击后退按钮退出应用程序时显示警告

时间:2012-11-05 07:10:31

标签: android android-alertdialog

我想知道当用户尝试退出应用时你会出现警告?所以这包括他们是否也按下后退按钮。最好的方法是什么?

我已经在一些主流游戏中看到了这一点。

2 个答案:

答案 0 :(得分:7)

您可以在onBackPressed()子类中添加Application来拦截后退按钮:

public static void onBackPressed(final Activity activity) {
    AlertDialog.Builder builder = new AlertDialog.Builder(activity);
    builder.setTitle(R.string.on_back_button_title);
    builder.setMessage(R.string.on_back_button_message);
    builder.setPositiveButton(R.string.yes, new OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            activity.finish();
        }
    });
    builder.setNegativeButton(R.string.no, new OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

        }
    });
    builder.show();
}

答案 1 :(得分:-1)

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    /*if (keyCode == KeyEvent.KEYCODE_HOME) {
        Log.i("Home Button", "Clicked");
        // Toast.makeText(this,"Home Button Clicked",Toast.LENGTH_LONG).show();
        return false;
    }*/  // You cannot gain control over home button

    if (keyCode == KeyEvent.KEYCODE_BACK) {
        Toast.makeText(this, "Press back Button to pause Evaluation",
                Toast.LENGTH_LONG).show();
        Log.i("Back Button", "Clicked");
        return false;
        // finish();
    }
    return false;
}