如何在运行时更改布局<fragment>中定义的片段:



我正在用一个"android.support.design.widget.BottomNavigationView"构建一个活动(MainActivity.kt(,它有多个选项卡。当用户点击选项卡时,"BottomNavigationView.OnNavigationItemSelectedListener"应该会显示相应的片段。

问题:

如何在onCreateView方法的运行时通过"android:name"属性设置与布局文件中定义的片段不同的片段。

主活动.kt

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)
}

Layout/ActivityMain.xml


<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.developer.myapplication.Locator"
android:id="@+id/fragment"
/>
<android.support.design.widget.BottomNavigationView
android:id="@+id/navigation"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="@menu/navigation"
app:layout_constraintTop_toBottomOf="@+id/fragment"
app:layout_constraintStart_toStartOf="parent"/>
</android.support.constraint.ConstraintLayout>

如果您想在运行时更改片段,您应该使用FrameLayout作为片段的容器,而不是使用片段标记。一旦使用FrameLayout,就可以很容易地在运行时交换片段;您只需使用getFragmentManager((.beginTransaction((.replace(R.id.FrameLayoutId,new MyFragment(((.commit((即可。此外,您通常会对要保留的片段使用fragment标记(这意味着您不打算在运行时替换或修改它们(。有关更多信息,您可以看看主细节视图是如何用片段实现的(Android:我什么时候/为什么应该使用FrameLayout而不是Fragment?(

希望这能有所帮助!:(

最新更新