自己记录 直接上流程具体方法理解看别人的博客吧
项目build添加
def nav_version = "2.3.0-alpha01" classpath "androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version"
app build添加 按需添加
apply plugin: "androidx.navigation.safeargs.kotlin"
implementation 'androidx.navigation:navigation-fragment:2.3.0-alpha01' implementation 'androidx.navigation:navigation-ui:2.3.0-alpha01' implementation 'androidx.navigation:navigation-fragment-ktx:2.3.0-alpha01' implementation 'androidx.navigation:navigation-ui-ktx:2.3.0-alpha01' implementation 'androidx.navigation:navigation-dynamic-features-fragment:2.3.0-alpha01' implementation 'androidx.navigation:navigation-testing:2.3.0-alpha01'
res创建navigation文件夹
生成nav_graph.xml文件 想里面添加主activity和其他fragment
<?xml version="1.0" encoding="utf-8"?> <navigation 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/nav_graph" tools:ignore="MissingDefaultResource" app:startDestination="@id/page1Fragment"> <fragment android:id="@+id/page1Fragment" android:name="com.kotlin.study.mykotlin.android.jetpack.navigation.Page1Fragment" android:label="Page1Fragment" > <action android:id="@+id/action_page1Fragment_to_page2Fragment" app:destination="@id/page2Fragment" /> <action android:id="@+id/action_page1Fragment_to_page3Fragment2" app:destination="@id/page3Fragment" /> </fragment> <fragment android:id="@+id/page2Fragment" android:name="com.kotlin.study.mykotlin.android.jetpack.navigation.Page2Fragment" android:label="Page2Fragment" /> <fragment android:id="@+id/page3Fragment" android:name="com.kotlin.study.mykotlin.android.jetpack.navigation.Page3Fragment" android:label="Page3Fragment" /> </navigation>
activity布局文件设置
<fragment android:id="@+id/nav_host_fragment" android:name="androidx.navigation.fragment.NavHostFragment" android:layout_width="match_parent" android:layout_height="match_parent" app:defaultNavHost="true" app:navGraph="@navigation/nav_graph" />
跳转的话就随便写获取管理器通过id或者action跳转都可以
Navigation.findNavController(it).navigate(R.id.action_page2Fragment_to_page3Fragment)