在Android中按下后退按钮后显示消息

时间:2014-03-09 09:20:46

标签: android

按下后退按钮后,我使用以下代码转到其他活动。

@Override
    public void onBackPressed() {
        Intent in = new Intent("com.test.START");
        startActivity(in);
    }

我应该如何编辑代码以显示一个对话框,要求用户返回或留在当前活动中?

2 个答案:

答案 0 :(得分:1)

您可以使用以下代码:

   @Override
    public void onBackPressed() {
           new AlertDialog.Builder(this)
                    .setIcon(android.R.drawable.ic_dialog_alert)  // icon that you want
                    .setTitle(R.string.alarm)  // title of your dialog
                    .setMessage(R.string.confirmedMessage)  // message of dialog
                    .setPositiveButton(R.string.yes,  // String for positive 
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog,
                                        int which) {
                                   // do positive action here

                                    finish();
                                }
                            }).setNegativeButton(R.string.no, // String for negative action
                                     null).show();

}

要返回,您可以使用完成()方法,而不是启动其他活动

答案 1 :(得分:1)

嗯,根据你的代码你不会回去,你开始另一项活动,但无论如何它可以按照以下方式完成:

@Override
public void onBackPressed() {
    (new AlertDialog.Builder(this))
            .setTitle("Confirm action")
            .setMessage("Do you want to ...?")
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Intent in = new Intent("com.test.START");
                    startActivity(in);
                    finish();
                }
            })
            .setNegativeButton("No", null)
            .show();
}
相关问题