Android Fragments recreated on orientation change

后端 未结 4 2094
有刺的猬
有刺的猬 2020-12-17 15:42

I\'m developing an app that basically has an ActionBar. When my app starts, the Activity creates the fragments and attaches them to each tab, so when I switch I get differen

4条回答
  •  忘掉有多难
    2020-12-17 15:57

    I am not sure if there is a better solution, but this is what i did in latest program.

    When a fragment is created automatically by system on orientation change and if you want to keep track of them in host activity, catch them in host activity's OnAttachFragment() method. And they get the arguments by default, so you can use them to find out which fragment it is.

       public void onAttachFragment(Fragment fragment) {
        super.onAttachFragment(fragment);
        if (fragment != null) {
            if(fragment.getArguments() != null) {
                switch (fragment.getArguments().getString(ARG_PARAM1)) {
                    case FragmentATag:
                        if (myFragmentA != fragment) {
                            myFragmentA = (FragmentA) fragment;
                        }                     
                        break;
                    case FragmentBTag:
                        if (myFragmentB != fragment) {
                            myFragmentB = (FragmentB) fragment;
                        }                        
                        break;                  
                }
            }
         }
       }
    

提交回复
热议问题