1

我的应用程序上有此代码

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {


        Intent a = new Intent(this,a_stages.class);
        a.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(a);
        return true;
    }
    return super.onKeyDown(keyCode, event);
}       

现在我想添加一个警告对话框,询问用户他/她是否想去,例如在另一个页面上,如果用户点击是,它将意图进入特定页面,如果用户点击取消,对话框。取消();。

编辑 我尝试了这段代码,但在“Intent a = new Intent(this,a_stages.class);”行出现错误 上面写着“构造函数 Intent(new DialogInterface.OnClickListener(){}, Class) 未定义”

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {

        AlertDialog.Builder alertDialog = new AlertDialog.Builder(bq1.this);

        // Setting Dialog Title
        alertDialog.setTitle("Go back to home");

        // Setting Dialog Message
        alertDialog.setMessage("Are you sure you want to go back to home?");



        // Setting Positive "Yes" Button
        alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {

                 Intent a = new Intent(this,a_stages.class);
                a.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(a);
            }
        });

        // Setting Negative "NO" Button
        alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            // Write your code here to invoke NO event

            dialog.cancel();
            }
        });

        // Showing Alert Message
        alertDialog.show();


    }
    return super.onKeyDown(keyCode, event);
}       
4

2 回答 2

1

很近!您需要return false在按下返回键时使用,return super.onKeyDown()否则。像这样:

if (keyCode == KeyEvent.KEYCODE_BACK) {
    // Dialog code
    return false;
}
return super.onKeyDown(keyCode, event);

onBackPressed()(如果您只对听后退键感兴趣,也可以改写。)

于 2013-01-22T17:31:47.850 回答
1

Intent a = new Intent(this,a_stages.class);中,this是指您的匿名点击监听器。您需要显式引用包含类,例如

Intent a = new Intent(MyActivity.this,a_stages.class); 

MyActivity此代码所在的活动名称在哪里。

于 2013-01-22T17:35:46.727 回答