我正在覆盖 Activity 中的 onBackPressed 方法:
@Override
public void onBackPressed() {
super.onBackPressed();
}
我正在按如下方式添加 fragment :
fragmentManager.beginTransaction()
.add(R.id.frame_container, myFragment).addToBackStack("").commit();
问题是我的 onBackPressed 没有在 Activity 中被调用。 但是当我把它改成:
replace(R.id.frame_container, myFragment).addToBackStack("").commit();
它按预期被调用。 我必须添加 fragment 。如何解决这个问题?
最佳答案
@Override
public boolean onKeyUp(int keyCode, KeyEvent objEvent) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
onBackPressed();
return true;
}
return super.onKeyUp(keyCode, objEvent);
}
@Override
public void onBackPressed() {
goBack();
}
public void goBack() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
MyCaseActivity.this);
alertDialog.setTitle("");
alertDialog.setMessage("Are you sure you want to exit?");
alertDialog.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
System.exit(0);
}
});
alertDialog.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
这对我有用。
关于android - 为什么 Activity 的 onBackPressed 没有被调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32668015/