Fragments within Fragments

前端 未结 6 712
名媛妹妹
名媛妹妹 2020-11-22 09:47

I\'m wondering if this is actually a bug in the Android API:

I have a setup like so:

┌----┬---------┐
|    |         |
|  1 |    2    |
|    |┌------         


        
6条回答
  •  温柔的废话
    2020-11-22 10:15

    I've faced with the same problem, have struggled a couple of day with it and should say that the most easiest way to overcome I found this is to use fragment.hide() / fragment.show() when tab is selected/unselected().

    public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft)
    {
        if (mFragment != null)
            ft.hide(mFragment);
    }
    

    When screen rotation occurs all parent and child fragments get correctly destroyed.

    This approach has also one additional advantage - using hide()/show() does not cause fragment views to loose their state, so there is no need to restore the previous scroll position for ScrollViews for example.

    The problem is that I don't know whether it is correct to not detach fragments when they are not visible. I think the official example of TabListener is designed with a thought in mind that fragments are reusable and you should not pollute with them memory, however, I think if you have just a few tabs and you know that users will be switching between them frequently it will be appropriate to keep them attached to the current activity.

    I would like to hear comments from more experienced developers.

提交回复
热议问题