简介
Navigation导航编辑器旨在简化Android开发中导航的实现,可以帮助我们很好的处理Activity和fragment之间通过FragmentTransaction交互的复杂性,也可以很好的处理页面的转场效果;Deeplink的支持,绕过activity直接跳到fragment;并且传递参数更安全。在Android Studio3.2可以使用。
基本使用
- 引用相关依赖
implementation "android.arch.navigation:navigation-fragment:1.0.0-rc01" // use -ktx for Kotlin
implementation "android.arch.navigation:navigation-ui:1.0.0-rc01"
- 创建资源文件
- 创建Fragment文件
class IndexFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.index_fragment, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
var args = arguments?.let { IndexFragmentArgs.fromBundle(it) }
top_bar_title.text = args!!.topBarTitle
txt_desc.text = "${args!!.topBarTitle}页面"
}
}
class BallFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.ball_fragment, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
var args = arguments?.let { BallFragmentArgs.fromBundle(it) }
top_bar_title.text = args!!.topBarTitle
txt_desc.text = "${args!!.topBarTitle}页面"
}
}
- 创建navigation导航图
<?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"
app:startDestination="@id/indexFragment">
<!-- app:startDestination是起始Destination,必须指定 -->
<fragment android:id="@+id/indexFragment"
android:name="com.fomin.demo.bar.IndexFragment"
android:label="IndexFragment"
tools:layout="@layout/index_fragment">
<!--参数传递-->
<argument android:name="topBarTitle"
app:argType="string"
android:defaultValue="主页"/>
<!--跳转动作-->
<action android:id="@+id/action_indexFragment_to_ballFragment"
app:destination="@id/ballFragment"/>
</fragment>
<fragment android:id="@+id/ballFragment"
android:name="com.fomin.demo.bar.BallFragment"
android:label="BallFragment"
tools:layout="@layout/ball_fragment">
<argument android:name="topBarTitle"
app:argType="string"
android:defaultValue="足球"/>
</fragment>
</navigation>
- Activity布局文件添加fragment
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
androi