Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onDetach called when fragment

Im having a trouble displaying the same fragment after orientation change. Im putting it to backstack and popping back. It jumps to onCreateView and so on, but then it is calling onDetach, which causes to display wrong fragment.. the code is like:

    //fragment
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {...}

    @Override
public void onDetach() {
    super.onDetach();
    this.getActivity().getFragmentManager().beginTransaction().addToBackStack(null);
}

and in main

    if (getFragmentManager().getBackStackEntryCount()>1){
        setContentView(R.layout.activity_main);
        getFragmentManager().popBackStack();
    }

im i missing something? Thanks for help in advance

like image 594
Martin Avatar asked Oct 19 '22 20:10

Martin


1 Answers

Whenever you change the orientation, your Activity gets recreated and hence the fragment hosted within your Activity gets recreated and so your fragments entire lifecycle methods are getting called again.

If you want to handle the configuration changes using fragments, please check the below link: http://www.androiddesignpatterns.com/2013/04/retaining-objects-across-config-changes.html

like image 181
miteshpithadiya Avatar answered Oct 22 '22 09:10

miteshpithadiya