(转)Activity中多fragment使用NavHostFragment导航用法


会自动添加fragment依赖

implementation 'androidx.navigation:navigation-fragment-ktx:2.3.0'
implementation 'androidx.navigation:navigation-ui-ktx:2.3.0'

容器nav_container,用来放fragment

<?xml version="1.0" encoding="utf-8"?>
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/nav_container"
app:startDestination="@id/nav1Fragment">

android:id="@+id/nav1Fragment"
android:name="com.bliss.myapp.Nav1Fragment"
android:label="fragment_nav1"
tools:layout="@layout/fragment_nav1" >
android:id="@+id/action_nav1Fragment_to_nav2Fragment2"
app:destination="@id/nav2Fragment"
app:popEnterAnim="@anim/slide_in_left"
app:popExitAnim="@anim/slide_out_right"
app:enterAnim="@anim/slide_in_right"
app:exitAnim="@anim/slide_out_left"/>

android:id="@+id/nav2Fragment"
android:name="com.bliss.myapp.Nav2Fragment"
android:label="fragment_nav2"
tools:layout="@layout/fragment_nav2" />


activity中引用fragment容器
引用容器nav_container

android:id="@+id/nav_host_fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:navGraph="@navigation/nav_container"
android:name="androidx.navigation.fragment.NavHostFragment"/>


app:defaultNavHost=“true” 该Fragment会自动处理系统返回键,即,当用户按下手机的返回按钮时,系统能自动将当前的Fragment推出。
app:navGraph 设置该Fragment对应的导航图 。
容器中在design视图下创建fragment


fragment间跳转
view.findViewById