你好,
在我的 MainActivity 中添加
OnBackPressedDispatcher
和 OnBackPressedCallback
,因为 onBackPressed
已被弃用。
旧用法:
@Override
public void onBackPressed() {
//Display alert message when back button has been pressed
alertDialogShow();
}
新用法: 将其放入我的初始化侦听器调用中
MainActivity
onCreate()
- initListeners()
onBackPressedCallback = new OnBackPressedCallback(true) {
@Override
public void handleOnBackPressed() {
//Display alert message when back button has been pressed
alertDialogShow();
}
};
onBackPressedDispatcher = new OnBackPressedDispatcher();
onBackPressedDispatcher.addCallback(this,onBackPressedCallback);
但是alterDialogShow()方法永远不会被调用并且活动会立即终止。 我该如何解决这个问题。
谢谢, 亚历杭德罗
根据我上面的评论。这是一种方法。
OnBackPressedCallback onBackPressedCallback = new OnBackPressedCallback(true) {
@Override
public void handleOnBackPressed() {
// Create an AlertDialog to confirm the action
new AlertDialog.Builder(YourActivity.this)
.setTitle("Confirm Action")
.setMessage("Are you sure you want to go back?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Perform the desired action when the user confirms
// For example, you can call super.onBackPressed() to go back
super.onBackPressed();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Do nothing or handle the cancel action here
}
})
.show();
}
};
// Add the callback to the back stack
getOnBackPressedDispatcher().addCallback(this, onBackPressedCallback);
}