【Android】Navigation实现页面跳转 |
您所在的位置:网站首页 › 页面跳转中请用笔记好 › 【Android】Navigation实现页面跳转 |
接下来我会通过一个例子,让大家在10分钟之内掌握和完成Navigation的基本使用。 需要完成四个页面 MainActivityFirstFragmentSecondFragmentThirdFragment![]() 通常在navigation文件下创建xml文件来配置页面的跳转信息 标签定义所有Fragment页面,标签定义页面跳转的配置信息:即通过指定android:id跳转到app:destination,navigation_graph.xml类似AndroidManifest中的作用 4. 应用navigation_graph(2分钟)navigation_graph无法直接应用在Activity上,需要通过一个HostFragment进行配置 经过以上配置后,就可以在各个Fragment中实现页面跳转 //FirstFragment class FirstFragment : Fragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.fragment_first, container, false) view.button.setOnClickListener { findNavController().navigate(R.id.action_first_to_second) } return view } } //SecondFragment class SecondFragment : Fragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.fragment_second, container, false) view.button.setOnClickListener { findNavController().navigate(R.id.action_second_to_third) } return view } } //ThirdFragment class ThirdFragment : Fragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.fragment_third, container, false) view.button.setOnClickListener { findNavController().navigate(R.id.action_third_to_first) } return view } }10分钟完成了基本的页面跳转。 5. 跳转动画最后我们再花点时间为页面跳转加上动画,提高使用体验 navigation_graph.xml内中配置动画资源 也可以通过配置app:popEnterAnim、app:popExitAnim实现Dialog弹出的效果 6. popBackStacknavigation使用FragmentManager的stack管理页面的回退,点击back键后可以回退前一个页面,我们也可以通过popBackStack方法从ThirdFragment直接回到FirstFragment class ThirdFragment : Fragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.fragment_third, container, false) view.button.setOnClickListener { findNavController().popBackStack(R.id.firstFragment, false) } return view } } 最后本文简单介绍了如何使用Navigation实现页面跳转,Navigation更多用法,例如与Toolbar的配合、Deeplink等,欢迎从官网进行学习查阅 The Navigation Architecture Component |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |