――When I was creating a certain app, I wanted to put in a process to disable the back button, so a memorandum --For Activity, you can just override OnBackPressed, but for fragment, that's not the case.
MyActivity.java
@Override
public void onBackPressed() {
//Insert the processing when the back button is pressed
}
--You can pass the value via Interface, but it is troublesome to specify the ID and tag. .. .. --I was looking for an easier way, and it seems that it can be implemented only within Fragment by using OnBackPressedDispatcher. (It was the fastest when I looked at the document from the beginning ...)
MyFragment.java
public class MyFragment extends Fragment {
private OnBackPressedCallback mBackButtonCallback;
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
@Override
public void onCreate(Bundle savedInstanceState) {
mBackButtonCallback = new OnBackPressedCallback(true) {
@Override
public void handleOnBackPressed() {
//Insert the processing when the back button is pressed
}
};
requireActivity().getOnBackPressedDispatcher().addCallback(this, mBackButtonCallback);
}
@Override
public void onDestroy(){
mBackButtonCallback.remove();
super.onDestroy();
}
}
――It's very easy, but when implementing this, if you do not explicitly release the callback by remove () with onDestroy etc., the process will be executed in other Fragment etc. ――It doesn't mean that you will release it without permission, so I think you need to be careful about that point.
Recommended Posts