Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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() {
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

You have to override onBackPressed of parent FragmentActivity class. Therefore, put your codes in parent FragmentActivity. Or you can call parent's method by using this:

public void callParentMethod(){
    getActivity().onBackPressed();
}

in FragmentActivity override onBackPressed Method and not call its super class to disable back button.

@Override
public void onBackPressed() {
  //super.onBackPressed();
  //create a dialog to ask yes no question whether or not the user wants to exit
  ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...