我正在打开警报对话框活动。一切都很好,唯一的问题是用户在AndroidCommand活动中按下 - alertdialog完全打开,但再次按下后退按钮 - 只是对话框关闭,而不是对话框活动。所以它需要两次背压才能回到AndroidCommand活动。取消对话框时,如何关闭活动对话框?
public class AndroidCommand extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (KeyEvent.KEYCODE_BACK == event.getKeyCode()) {
Intent intent = new Intent(AndroidCommand.this, MainActivity.class);
startActivity(intent);
return true;
}
return super.onKeyDown(keyCode, event);
}
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final String items[] = {"Movie","Music","Book"};
AlertDialog.Builder ab=new AlertDialog.Builder(MainActivity.this);
ab.setTitle("Dialog Title");
ab.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface d, int choice) {
if(choice == 0) {
}
else if(choice == 1) {
}
else if(choice == 2) {
}
}
});
ab.show();
}
答案 0 :(得分:0)
这是完整的解决方案
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
if (!isBack)
showDialog();
else
isBack = true;
return true;
}
else
return super.onKeyDown(keyCode, event);
}
在oncreatemethod中初始化isBack = false
void showDialog () {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Alert");
builder.setMessage("Are you sure you want to exit?");
builder.setPositiveButton("OK", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
builder.setNegativeButton("Cancel", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
isBack = false;
}
});
builder.show();
}
答案 1 :(得分:0)
呼叫
finish()
按下后退方法
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (KeyEvent.KEYCODE_BACK == event.getKeyCode()) {
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
答案 2 :(得分:0)
只是覆盖,
@Override
public void onBackPressed() {
// TODO Auto-generated method stub
// super.onBackPressed();
new AlertDialog.Builder(this)
.setTitle("Dictation Alert")
.setIcon(R.drawable.galleryalart)
.setMessage("Do You want save dictation??")
.setNegativeButton(android.R.string.no, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//do other stuff here
finish()
}
})
.setPositiveButton("yes", new OnClickListener() {
//do other stuff here
finish()
}).show
}