简介
安卓开发中,Activity的使用较为简单,而Fragment则令人头疼,使用非常复杂。为了改善此种情况,Google 在2018 I/O大会上推出了JetPack,而Navigation则是和页面切换相关的。
使用方法
- build.gradle中添加依赖
implementation 'android.arch.navigation:navigation-fragment:1.0.0-rc02'
-
添加navigation文件.
1)鼠标右键点击“res”目录,选择“New”》“Android Resource Directory”
2)选择“navigation”
3)鼠标右键点击“navigation”目录,选择“New”》“Navigation resource file”
4)通过界面拖拽或者直接编辑导航文件
<?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"
android:id="@+id/navi_main"
app:startDestination="@id/firstFragment">
<fragment
android:id="@+id/firstFragment"
android:name="com.cxyzy.navigationdemo.FirstFragment"
android:label="FirstFragment">
<action
android:id="@+id/action_firstFragment_to_secondFragment"
app:destination="@id/secondFragment" />
</fragment>
<fragment
android:id="@+id/secondFragment"
android:name="com.cxyzy.navigationdemo.SecondFragment"
android:label="SecondFragment" >
</fragment>
</navigation>
- 跳转(含传参)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
gotoSecondFragmentBtn.setOnClickListener {
Navigation.findNavController(it).navigate(R.id.action_firstFragment_to_secondFragment, Bundle().apply {
putString("name", "jenny")
putInt("age", 18)
})
}
}
- 接收参数(下面的navigateUp是返回的意思)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
arguments?.let {
infoTextView.text = "上页传入数据:name:" + it.getString("name") + ";age:" + it.getInt("age", 0)
}
gotoFirstFragmentBtn.setOnClickListener {
Navigation.findNavController(it).navigateUp()
}
}
-
实现效果
源代码
https://gitee.com/cxyzy1/navigationDemo
附录
navigation官方介绍文档:https://codelabs.developers.google.com/codelabs/android-navigation/#0
其他参考资料:
https://www.jianshu.com/p/729375b932fe
https://blog.csdn.net/mq2553299/article/details/80445952
https://blog.csdn.net/cekiasoo/article/details/80739805
安卓开发技术分享: https://www.jianshu.com/p/442339952f26
更多技术总结好文,请关注:「程序园中猿」
网友评论