Why is an extra FrameLayout created for fragments?

后端 未结 1 1791
醉梦人生
醉梦人生 2021-01-01 23:24

While using the hierarchy viewer in order to reduce hierarchies, I\'ve noticed that on each addition of a fragment (both in \"static\" or \"dynamic\" way) the fragments is a

相关标签:
1条回答
  • It seems like you are using the support v4 library and you forgot to put and id to your fragment xml tag :), so:

    where did it come from?

    It comes from line 888 of FragmentManager where you can see this:

    f.mView = NoSaveStateFrameLayout.wrap(f.mView);
    

    The reason for this is backwards compatibility and it is better explained in the comment header of NoSaveStateFrameLayout which says:

    /**
     * Pre-Honeycomb versions of the platform don't have {@link View#setSaveFromParentEnabled(boolean)},
     * so instead we insert this between the view and its parent.
     */
    

    can I get rid of it?

    Well, I can think of three options:

    1. You could have your very own implementation of FragmentManager say based on support v4 library version in which you omit this container, but I think the effort of writing/maintaining that code is not worth, plus I don't think the overhead due those FrameLayouts is gigantic, if you are having performance issues you probably have other View optimizations to perform besides this (say write a custom view -which extends View-) or say rethink your layout/fragments to reduce the amount of views in the hierarchy at certain point.
    2. Wait for a new release of support v4 library which accomplishes 1. <- yup I'm a lazy person :D, you'll have to file a bug if there is not one already (see 3.), the cool part of this is you could even contribute your patch or someone else as well.
    3. Support only platforms (or wait until) where the support v4 library is not (longer) needed, in API level 11+ FragmentManager implementation does not have this nested ViewGroup (see line 861 of 11+ FragmentManager), on those you get something like this:

    Look mom!, no nested <code>FrameLayout</code>!!1

    I wouldn't worry much for those as I mentioned there are other optimizations you can invest that time in ;)

    0 讨论(0)
提交回复
热议问题