同时使用 hierarchy viewer为了减少层次结构,我注意到在每次添加 fragment 时(以“静态”或“动态”方式), fragment 总是包裹在一个新的FrameLayout中。
这是一个例子:
这是我的 Activity 布局:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:contentDescription="mainActivityRoot" >
<TextView
android:id="@+id/hello_world"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<fragment
android:name="com.example.testfragments.MainFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/hello_world" />
</RelativeLayout>
这是 fragment 布局:
<ProgressBar android:id="@+id/ProgressBar1" xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:contentDescription="mainFragmentRoot"
android:layout_height="match_parent" />
除了setContentView
,Activity源代码是空的,
fragment 源代码仅包含
@Override
public View onCreateView(...) {
return inflater.inflate(R.layout.fragment_main, container, false);
}
现在,
我希望直接在 Activity 根的层次结构中看到 PrograssBar
,但是有一个额外的 FrameLayout,我不知道它来自哪里。
这是一个屏幕截图,将额外的框架涂成黄色:
所以,我的问题是 - 它是从哪里来的?我可以摆脱它吗? 在我的实际应用程序中,那些额外的 FrameLayouts 正在创建非常深的层次结构,这可能对性能不利。
谢谢!
最佳答案
看起来你正在使用支持 v4 库,你忘记将和 id 放入你的 fragment xml 标签:),所以:
where did it come from?
来自line 888 of FragmentManager在哪里可以看到:
f.mView = NoSaveStateFrameLayout.wrap(f.mView);
这样做的原因是向后兼容,在 NoSaveStateFrameLayout
的注释标题中有更好的解释,它说:
/**
* 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?
嗯,我可以想到三个选项:
- 你可以有你自己的
FragmentManager
实现说基于支持 v4 库版本,你在其中省略了这个容器,但我认为编写/维护该代码的努力是不值得的,另外我不要认为这些FrameLayout
的开销是巨大的,如果您遇到性能问题,您可能还需要执行其他View
优化(比如编写自定义 View -extends View
-) 或者说重新考虑您的布局/fragment 以在特定点减少层次结构中的 View 数量。 - 等待完成 1 的支持 v4 库的新版本。 <- 是的,我是一个懒惰的人 :D,如果还没有错误,你将不得不提交错误 (参见 3.),最酷的部分是您甚至可以贡献您的补丁或其他人。
- 仅支持(或等到)不需要(不再)支持 v4 库的平台,在 API 级别 11+
FragmentManager
实现中没有此嵌套的ViewGroup
(见 line 861 of 11+FragmentManager
),在那些你得到这样的东西:
正如我提到的那样,我不会太担心那些您可以投入时间进行其他优化;)
关于android - 为什么要为 fragment 创建一个额外的 FrameLayout?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16774781/