jetPack组件必学#Navigation

45 阅读1分钟

jetPack组件必学#Lifecycle

jetPack组件必学#LiveData&ViewMode

jetPack组件必学#DataBinding

jetPack组件必学#Dagger2&Hilt

jetPack组件必学#Navigation

jetPack组件必学#Room

一.Navigation是什么?

Navi是jetPack的Ui组件,它使用于单个Activity多个Fragment,可以结合底部和顶部以及侧边导航栏,管理起来更加灵活,而且它也支持DeepLink。

二.Navigation怎么用?

1.Navigation三大元素

1.Fragment容器:NaviHostFragment

2.Fragment导航图:navi_gragh

3.Fragment跳转:NaviController

2.跳转实列

   override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        view.findViewById<TextView>(R.id.tv2)
            .setOnClickListener {
                findNavController().navigate(R.id.action_fragmentB2_to_fragmentC22) //根据naviGraph跳转
            }
        view.findViewById<TextView>(R.id.tv4).setOnClickListener {
            findNavController().navigateUp() //类似于返回键
        }
    }

3.参数传递

   view.findViewById<TextView>(R.id.tv1)
            .setOnClickListener {
                findNavController().navigate(R.id.action_fragmentA2_to_fragmentB22,

                   Bundle().apply {
                        putString("param1", "FragmentA") //传递参数
                    }
                )
            }

4.安全参数传递

5.结合BottomNavigationView、Appbar、ToolBar使用

val navHostFragment: Fragment =
    supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment

//找到Controller
val navController = navHostFragment.findNavController()


//底部导航栏
val bottomNavigationView: BottomNavigationView = findViewById(R.id.nav_bottom)


//绑定底部导航栏和Navigation
NavigationUI.setupWithNavController(bottomNavigationView,navController)
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto">

  <item
    android:id="@+id/fragmentA2"
    android:title="Item1" />
  <item
    android:id="@+id/fragmentB2"
    android:title="Item2" />
  <item
    android:id="@+id/fragmentC2"
    android:title="Item3" />
</menu>

6.DeepLink的配置

1.在navigrah中配置Fragment的deepLink

<fragment
  android:id="@+id/fragmentB2"
  android:name="com.seven.nav.FragmentB"
  android:label="fragment_b"
  tools:layout="@layout/fragment_b">
  <action
    android:id="@+id/action_fragmentB2_to_fragmentC22"
    app:destination="@id/fragmentC2" />
  <action
    android:id="@+id/action_fragmentB2_to_fragmentA2"
    app:popUpTo="@id/fragmentA2" />
  <deepLink
    android:id="@+id/deepLink"
    app:action="ACTION_BAIDU"
    app:mimeType="test/fragment"
    app:uri="www.baidu.com" />
</fragment>

2.指令测试

adb shell am start -W -a ACTION_BAIDU -d "www.baidu.com/test/fragment"  com.seven.nav/.MainActivity