如何操作后退按钮?
How to manipulate back button?
当我按下后退按钮时,我希望它能像 intent 一样工作,转到某些特定 activity 并刷新页面。我发现一些代码以这种方式工作,但找不到完全符合我要求的代码。提前致谢。
只需覆盖 activity 中的 onBackPressed 方法,如:
@Override
public void onBackPressed() {
/** Write your code here that you want to execute on Backpress**/
}
不要在 onBackPressed 中使用 super.onBackPressed()
因为它会调用父 activity onBackPressed
方法并终止当前 activity.
在你的activity中,你需要使用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();
}
小心 Android 上的后退导航。
有几条规则需要遵守:https://developer.android.com/training/implementing-navigation/temporal
https://developer.android.com/training/design-navigation/ancestral-temporal
试试下面的代码..
@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);
}
当我按下后退按钮时,我希望它能像 intent 一样工作,转到某些特定 activity 并刷新页面。我发现一些代码以这种方式工作,但找不到完全符合我要求的代码。提前致谢。
只需覆盖 activity 中的 onBackPressed 方法,如:
@Override
public void onBackPressed() {
/** Write your code here that you want to execute on Backpress**/
}
不要在 onBackPressed 中使用 super.onBackPressed()
因为它会调用父 activity onBackPressed
方法并终止当前 activity.
在你的activity中,你需要使用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();
}
小心 Android 上的后退导航。 有几条规则需要遵守:https://developer.android.com/training/implementing-navigation/temporal https://developer.android.com/training/design-navigation/ancestral-temporal
试试下面的代码..
@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);
}