一、Navigation
1.创建NavigationGraph


2.添加NavHostFragment
在Activity布局文件的根节点下添加NavHostFragment
<fragment
android:id="@+id/nav_host_fragment"
app:defaultNavHost="true"
app:navGraph="@navigation/nav_graph"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
3.创建两个Fragment
创建MainFragment及SecondFragment,在MainFragment中创建按钮,用于导航到SecondFragment
4.创建destination
在创建的nav_graph.xml文件中,点击加号,选择fragment_main和fragment_second,添加到可视面板中

5.创建action
将鼠标放到mainfragment右侧圆点上,并拖拽到右侧secondFragment,创建action

?
6.使用NavController完成导航
在MainFragment中onCreateView()方法中添加如下代码实现导航跳转,这里有两种方式实现导航
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_main, container, false)
//方式一
view.findViewById<Button>(R.id.btntoSecondFragment)
.setOnClickListener {
Navigation.findNavController(view)
.navigate(R.id.action_mainFragment_to_secondFragment)
}
//方式二
view.findViewById<Button>(R.id.btntoSecondFragment)
.setOnClickListener(Navigation.createNavigateOnClickListener(R.id.action_mainFragment_to_secondFragment))
return view
}
7.添加动画
创建动画文件,并在nav_graph.xml中选中action箭头,在右侧属性中添加动画


二、使用safe args插件传递参数
1.配置gradle
在Project的build.gradle文件中dependencied层级,添加classpath
classpath 'androidx.navigation:navigation-safe-args-gradle-plugin:2.3.3'
在Module的build.gradle中添加插件
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'kotlin-kapt'
id 'androidx.navigation.safeargs'
}
2.添加argument
在nav_graph.xml文件中,mainfragment中添加<argument>标签
<argument
android:name="user_name"
app:argType="string"
android:defaultValue="unknown" />
<argument
android:name="age"
app:argType="integer"
android:defaultValue="0" />
3.在MainFragment中传参
val bundle=MainFragmentArgs.Builder()
.setUserName("zy")
.setAge(27)
.build()
.toBundle()
Navigation.findNavController(view)
.navigate(R.id.action_mainFragment_to_secondFragment,bundle)
4.在SecondFragment中接收参数
val userName=MainFragmentArgs.fromBundle(requireArguments()).userName
val age=MainFragmentArgs.fromBundle(requireArguments()).age
view.findViewById<TextView>(R.id.tv).text="userName: $userName \nage: $age"
|