Issue
I want to disable the back button in a fragment class. onBackPressed()
doesn't seem to work in this fragment. How could I disable the back button?
This is my sample code:
public class Login extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
,Bundle savedInstanceState) {
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.login, null);
return root;
}
public void onBackPressed() {
}
}
Solution
Updated Answer
You need to use the new OnBackPressedDispatcher
to handle on back callbacks. Then, you can show Are you sure dialog
to confirm the action.
OnBackPressedCallback callback = new OnBackPressedCallback(true) {
@Override
public void handleOnBackPressed() {
// create a dialog to ask yes no questions whether or not the user wants to exit
}
};
requireActivity().getOnBackPressedDispatcher().addCallback(this, callback);
Old Answer
The below method is deprecated.
You have to override onBackPressed
of the parent FragmentActivity
class. Therefore, put your codes in the parent FragmentActivity
. Or you can call the parent's method by using this:
public void callParentMethod(){
getActivity().onBackPressed();
}
in FragmentActivity
override onBackPressed
Method and not call its superclass to disable the back button.
@Override
public void onBackPressed() {
// super.onBackPressed();
// create a dialog to ask yes no question whether or not the user wants to exit
...
}
Answered By - Gunhan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.