与片段更换活动只是覆盖上的前顶后 [英] Replacing activity with fragment just overlays latter on top of former
问题描述
当我尝试更换一个片段的活动,我的应用程序最终呈现在活动的顶部的片段:
When I try to replace an activity with a fragment, my app ends up rendering the fragment on top of the activity:
<!-- activity.xml -->
<CoordinatorLayout
android:id="@+id/coord_layout">
... stuff ...
</CoordinatorLayout>
下面是片段:
<!-- fragment.xml -->
<LinearLayout
android:id="@+id/frag_layout">
... stuff ...
</LinearLayout>
下面是我的主要类:
private void selectDrawerItem(MenuItem menuItem) {
Fragment f = fragment.newInstance();
FragmentManager fragManager = getSupportFragmentManager();
fragManager.beginTransaction().replace(R.id.coord_layout, f).commit();
}
我在做什么错了?
What am I doing wrong?
推荐答案
FragmentTransaction
团购只(动态创建的)片段
秒。任何查看
S中的容器内的ViewGroup
您使用的是按住片段
不受一个替换()
。也就是说,片段
将只是在上面补充说。如果你想完全取代现有的布局时,应更换 CoordinatorLayout
在 activity.xml
与空的ViewGroup
- 通常是的FrameLayout
- 并使用 CoordinatorLayout
作为布局另一个片段
,你可以在启动时,然后可以用相应的换出加载 FragmentTransaction
。
FragmentTransaction
s deal only with (dynamically created) Fragment
s. Any View
s within the container ViewGroup
you're using to hold the Fragment
are not affected by a replace()
. That is, the Fragment
will just be added on top of them. If you want to completely replace the existing layout, you should replace the CoordinatorLayout
in your activity.xml
with an empty ViewGroup
- usually a FrameLayout
- and use the CoordinatorLayout
as the layout for another Fragment
that you can load upon startup, which can then be swapped out accordingly with your FragmentTransaction
.
这篇关于与片段更换活动只是覆盖上的前顶后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!