Navigation
Navigation是用來管理Fragment的切換,重點是為了讓APP只有單個Activity多個Fragment。
name:必须是androidx.navigation.fragment.NavHostFragment。
navGraph="@navigation":創建好的navigation。
defaultNavHost="true":與返回鍵綁定。
navigation
startDestination:設置起始頁面。
1.fragment
name="class"綁定的Fragment類。
layout="@layout":顯示預覽圖。
2.action
popUpTo="@id":清除自己用。
popUpToInclusive="true":清除自己用。
destination="@id":要跳轉的頁面。
Gradle(Project)
classpath "androidx.navigation:navigation-safe-args-gradle-plugin:2.3.0"
Gradle(Module)
apply plugin: "androidx.navigation.safeargs.kotlin"
android {
kotlinOptions { jvmTarget = "1.8" }
}
dependencies {
def nav_version = "2.3.0"
implementation "androidx.navigation:navigation-fragment-ktx:$nav_version"
implementation "androidx.navigation:navigation-ui-ktx:$nav_version"
}
layout
<androidx.fragment.app.FragmentContainerView
android:id="@+id/navHost"
android:name="androidx.navigation.fragment.NavHostFragment"
app:defaultNavHost="true"
app:navGraph="@navigation/nav_graph"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
AFragment
class AFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_a, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
toB.setOnClickListener {
//通常要執行一次才會自動生成Directions這個方法
findNavController().navigate(AFragmentDirections.toB())
}
}
}
BFragment
class BFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_b, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
}
}
創建navigation(nav_graph.xml)
<?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.xml"
app:startDestination="@id/fragmentA"
tools:ignore="UnusedNavigation">
<fragment
android:id="@+id/fragmentA"
android:name="com.example.app_navigation_test.AFragment"
tools:layout="@layout/fragment_a">
<action
android:id="@+id/toB"
app:destination="@+id/fragmentB" />
</fragment>
<fragment
android:id="@+id/fragmentB"
android:name="com.example.app_navigation_test.BFragment"
tools:layout="@layout/fragment_b" />
</navigation>
刪除自己AFragment
<action
android:id="@+id/toB"
app:popUpTo="@id/AFragment"
app:popUpToInclusive="true"
app:destination="@id/BFragment" />