当我按下“后退”按钮时,我希望它可以像意图进行某些特殊活动并刷新页面那样工作。我发现一些代码以这种方式工作,但是找不到正在执行我想要的代码的代码。预先感谢。
答案 0 :(得分:0)
只需在您的活动中覆盖onBackPressed方法,例如:
@Override
public void onBackPressed() {
/** Write your code here that you want to execute on Backpress**/
}
请勿在onBackPressed中使用super.onBackPressed()
,因为它将被称为父活动onBackPressed
方法并杀死当前活动。
答案 1 :(得分:0)
在活动中,您需要使用 onBackPressed()
@Override
public void onBackPressed() {
//You'll put your code here, in my example below, i check if the user is sure
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to cancel?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
YourActivity.this.finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
答案 2 :(得分:0)
在Android上使用向后导航时要小心。 有几个要遵守的规则:https://developer.android.com/training/implementing-navigation/temporal https://developer.android.com/training/design-navigation/ancestral-temporal
答案 3 :(得分:0)
尝试以下代码。
@Override
public void onBackPressed() {
Log.d(TAG, "onBackPressed: GoTo NextActivity");
Intent intent = new Intent(getApplicationContext(),NextActivity.class); // Replace the NextActivity.class with the Activity you wish to open..
startActivity(intent);
}