Android片段替换自己的根视图
在我的Android片段替换自己的根视图,android,android-layout,android-fragments,Android,Android Layout,Android Fragments,在我的MainActivity的布局中有FrameLayout元素,它被用作多种类型片段的“连接点” 视图: <FrameLayout android:id="@+id/main_content" android:layout_width="match_parent" android:layout_height="match_parent" /> 现在我需要直接从CoursesFragment(fragment替换自己的视图)更改主要内容。最好的方法是什么?安全
MainActivity
的布局中有FrameLayout
元素,它被用作多种类型片段的“连接点”
视图:
<FrameLayout
android:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent" />
现在我需要直接从CoursesFragment
(fragment替换自己的视图)更改主要内容。最好的方法是什么?安全吗?我可以访问MainActivity
的上下文并对其进行更改,但我不知道这是否正确。我不知道您的视图是什么,但最简单的方法是在自己的视图组中提供两个视图,同时在设置可见性(View.GONE)
上设置“其他视图”。如果需要切换,只需将显示的第一个视图设置为View.GONE
,将第二个视图设置为View.VISIBLE
这样,您就不必对活动的上下文或片段管理器hide
和show
方法进行修改 我有两个以上的片段(视图),以这种方式在它们之间切换很尴尬。
Fragment fragment = new CoursesFragment();
getFragmentManager().beginTransaction().replace(R.id.main_content, fragment).commit();