我试图通过按后退按钮删除该对话框,在对话框上显示警告框。我在switch语句中创建了这个对话框。我通过使用每个可能的方面来尝试它,但它没有帮助 继承我的代码:
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
switch (arg2) {
case 0:
AlertDialog.Builder dialog = new AlertDialog.Builder(
Listitem.this);
dialog.setTitle("kya h");
dialog.setMessage("kuch ni");
dialog.setCancelable(true);
dialog.create();
dialog.show();
dialog.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialog,
int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_BACK) {
// finish();
// dialog.dismiss();
exitByBackKey();
}
return false;
}
private void exitByBackKey() {
// TODO Auto-generated method stub
AlertDialog.Builder alertbox = new AlertDialog.Builder(Listitem.this);
alertbox.setMessage("Do u want to exit");
alertbox.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
@Override
public void onClick(
DialogInterface dialog,
int which) {
// TODO Auto-generated
// method stub
finish();
dialog.cancel();
}
})
.setNegativeButton(
"No",
new DialogInterface.OnClickListener() {
@Override
public void onClick(
DialogInterface dialog,
int which) {
// TODO Auto-generated
// method stub
}
}).show();
}
});
break;
}
}
});
}
}
答案 0 :(得分:0)
要更改后退按钮的行为,您只需覆盖onBackPressed()
方法。
@Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage("Do u want to exit")
.setNegativeButton("No")
.setPositiveButton("Yes", new OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
finish();
dialog.cancel();
}
}).create().show();
}
确保dialog
方法可以访问onBackPressed()
。