我的应用程序中有此代码
@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);
}
现在我想添加一个警告对话框,询问用户他/她是否想要去,例如在另一个页面上,如果用户点击是,它将意图到特定页面,如果用户点击取消,dialog.cancel();.
修改 我尝试了这段代码,但我在“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);
}
答案 0 :(得分:1)
如此接近!按下后退键时需要使用return false
,否则需要return super.onKeyDown()
。像这样:
if (keyCode == KeyEvent.KEYCODE_BACK) {
// Dialog code
return false;
}
return super.onKeyDown(keyCode, event);
(如果您只想听取后退键,也可以覆盖onBackPressed()
。)
答案 1 :(得分:1)
在Intent a = new Intent(this,a_stages.class);
中,this
指的是您的匿名点击监听器。您需要显式引用包含类,如
Intent a = new Intent(MyActivity.this,a_stages.class);
其中MyActivity
是此代码所在活动的名称。