0%

Navigation入门

Navigation 组件由下面3个关键部分组成:

Navigation Graph XML resource 包含与navigation有关的所有信息,如destination path等。

NavHostFragment Layout XML 添加到layout的widget,显示了Navigation Graph的destination。

NavController Kotlin/Java 对象 追踪在 Navigation Graph 中的位置,协调那些destination。

Destinations

destination 是在app中可以导航到的地方,一般是fragment或activity。

一般来说,fragment作为destination。

Navigation Graph

NavController 此类用于控制在NavHostFragment中fragment的切换

1
2
3
Fragment.findNavController()
View.findNavController()
Activity.findNavController(viewId: Int)
1
2
3
4
val button = view.findViewById<Button>(R.id.navigate_destination_button)
button?.setOnClickListener(
Navigation.createNavigateOnClickListener(R.id.flow_step_one_dest, null)
)
1
2
3
4
5
6
// Note the usage of curly braces since we are defining the click listener lambda
view.findViewById<Button>(R.id.navigate_action_button)?.setOnClickListener {
val flowStepNumberArg = 1
val action = HomeFragmentDirections.nextAction(flowStepNumberArg)
findNavController().navigate(action)
}

更多 Navigation

drawer

bottom

1
2
3
4
5
6
7
8
9
val args = Bundle()
args.putString("myarg", "From Widget");
val pendingIntent = NavDeepLinkBuilder(context)
.setGraph(R.navigation.mobile_navigation)
.setDestination(R.id.deeplink_dest)
.setArguments(args)
.createPendingIntent()

remoteViews.setOnClickPendingIntent(R.id.deep_link_button, pendingIntent)

backstack

1
2
3
4
5
6
7
8
9
10
11
12
<fragment
android:id="@+id/deeplink_dest"
android:name="com.example.android.codelabs.navigation.DeepLinkFragment"
android:label="@string/deeplink"
tools:layout="@layout/deeplink_fragment">

<argument
android:name="myarg"
android:defaultValue="Android!"/>

<deepLink app:uri="www.example.com/{myarg}" />
</fragment>
1
2
3
4
5
6
7
8
9
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

<nav-graph android:value="@navigation/mobile_navigation" />
</activity>

2020-3-25 23:11:39