Android Jetpack 之Navigation Architecture Component使用

在刚刚结束的谷歌IO大会上,谷歌推出了Android Jetpack架构组件;正如官网所说,Android Jetpack 是一套组件、工具和指导,可以帮助您构建出色的 Android 应用。Android Jetpack 组件将现有的支持库与架构组件联系起来,并将它们分成四个类别:Architecture、Foundation、Behavior 以及 UI。他能够让开发者创造出更加出色的高质量应用。

Android Jetpack

Navigation导航编辑器作为Android Jetpack和 AndroidX 依赖库的一部分其目标旨在简化Android开发中导航的实现。Navigation可以帮助我们很好的处理Activity和fragment之间通过FragmentTransaction交互的复杂性。另外Navigation也可以很好的处理页面的转场效果。当然熟悉IOS开发的同学肯定看到这肯定会觉得这不就是StoryBoard么。关于Navigation的介绍,谷歌官方介绍的也不是很详细(英语太差!!!), 那么我们就动手实现个吧。

image

创建Android Jetpack 应用(Android Studio 3.2 Canary 13及更高版本)

image

添加依赖
  1. 项目的build.gradle:
1
2
3
4
5
6
7
8
9
10
buildscript {
...
repositories {
google()
}
dependencies {
...
classpath 'android.arch.navigation:navigation-safe-args-gradle-plugin:1.0.0-alpha01'
}
}
  1. 在app的build.gradle中添加如下依赖:
1
apply plugin: 'androidx.navigation.safeargs'
1
2
implementation 'android.arch.navigation:navigation-fragment:1.0.0-alpha01'
implementation 'android.arch.navigation:navigation-ui:1.0.0-alpha01'
创建导航编辑器

右键res资源文件夹 : New -> Android resource file -> 输入xml文件名称并选择Resource type为Navigation -> OK

image

1
2
3
4
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android">
</navigation>
给Activity添加导航视图

由于Navigation 中需要将fragment视图和activity绑定,那么接下来改造吧:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<fragment
android:id="@+id/my_nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="0dp"
android:layout_height="0dp"
app:defaultNavHost="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1"
app:navGraph="@navigation/main_navigation" />
</android.support.constraint.ConstraintLayout>

activity中fragment默认为NavHostFragment,NavHostFragment通过navGraph与navigation导航编辑器进行关联。
app:defaultNavHost=”true”可以让NavHostFragment处理系统的返回事件

编辑Navigation导航视图
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?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"
xmlns:tools="http://schemas.android.com/tools"
app:startDestination="@+id/main_fragment">
<fragment
android:name="com.wangjun.app.jetpacktodolist.ui.main.MainFragment"
android:id= "@+id/main_fragment"
android:label="@string/main_fragment_title"
tools:layout="@layout/main_fragment">
</fragment>
<activity
android:id="@+id/settings_activity"
android:name="com.wangjun.app.jetpacktodolist.ui.SettingActivity"
android:label="@string/activity_settings"
tools:layout="@layout/setting_activity"
/>
</navigation>

我们看到navigation标签声明了一个 app:startDestination=”@+id/main_fragment” 属性,他是导航器默认加载的视图

image

现在我们看到我们的导航编辑器又两个视图,main_fragment和 settings_activity,我们现在需要从main_fragment中跳转到 settings_activity的话,可以给main_fragment添加action标签来完成跳转

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?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"
xmlns:tools="http://schemas.android.com/tools"
app:startDestination="@+id/main_fragment">
<fragment
android:name="com.wangjun.app.jetpacktodolist.ui.main.MainFragment"
android:id= "@+id/main_fragment"
android:label="@string/main_fragment_title"
tools:layout="@layout/main_fragment">
<!--跳转到SettingActivity-->
<action
android:id="@+id/action_main_fragment_to_settings_activity"
app:destination="@id/settings_activity" />
</fragment>
<activity
android:id="@+id/settings_activity"
android:name="com.wangjun.app.jetpacktodolist.ui.SettingActivity"
android:label="@string/activity_settings"
tools:layout="@layout/setting_activity"
/>
</navigation>

action标签中的 app:destination 就是我们要加载导航的视图

当然我们也可以在导航编辑器中通过拖动来完成

image

接下来我们在MainFragment中添加一个按钮来完成跳转SettingActivity

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.main.MainFragment">
<android.support.v7.widget.AppCompatButton
android:id="@+id/btn_setting"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.5" />
</android.support.constraint.ConstraintLayout>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class MainFragment : Fragment() {
companion object {
fun newInstance() = MainFragment()
}
private lateinit var viewModel: MainViewModel
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View {
val view = inflater.inflate(R.layout.main_fragment, container, false)
view.findViewById<AppCompatButton>(R.id.btn_setting).setOnClickListener {
Navigation.findNavController(view).navigate(R.id.action_main_fragment_to_settings_activity)
}
return view
}
}

我们看到通过 Navigation.findNavController(view) 得到一个NavController,通过 NavController.navigate(R.id.xxxx) 会对应到当前View的某个Action,这样我们就可以跳转了。是不是很简单~~~

image

添加转场动画
添加转场动画也很简单,我们只需要在action添加如下属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<fragment
android:name="com.wangjun.app.jetpacktodolist.ui.main.MainFragment"
android:id= "@+id/main_fragment"
android:label="@string/main_fragment_title"
tools:layout="@layout/main_fragment">
<action
app:popEnterAnim="@anim/slide_in_left"
app:popExitAnim="@anim/slide_out_right"
app:enterAnim="@anim/slide_in_right"
app:exitAnim="@anim/slide_out_left"
android:id="@+id/action_main_fragment_to_settings_activity"
app:destination="@id/settings_activity" />
</fragment>

image

传递数据

和以前一样我们可以通过bundle传递数据

代码中手写

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<fragment
android:id="@+id/main2_fragment"
android:name="com.wangjun.app.jetpacktodolist.ui.main.Main2Fragment"
android:label="@string/main2_fragment_title"
tools:layout="@layout/main2_fragment">
<argument android:name="testArg"
app:type="string"
android:defaultValue="Hello Leon"
/>
<argument
android:name="testArg2"
android:defaultValue="大王叫我来巡山"
app:type="string" />
</fragment>

导航编辑器添加

image

MainFragment传参到 Main2Fragment

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class MainFragment : Fragment() {
companion object {
fun newInstance() = MainFragment()
}
private lateinit var viewModel: MainViewModel
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View {
val view = inflater.inflate(R.layout.main_fragment, container, false)
view.findViewById<AppCompatButton>(R.id.btn_setting).setOnClickListener {
Navigation.findNavController(view).navigate(R.id.action_main_fragment_to_settings_activity)
}
/**
* 参数跳转
*/
view.findViewById<AppCompatButton>(R.id.btn_main2).setOnClickListener {
val bundle = bundleOf("testArg" to "很高兴遇见你",
"testArg2" to "你是猴子派来的逗逼吗")
Navigation.findNavController(view).navigate(
R.id.action_main_fragment_to_main2_fragment,
bundle)
}
return view
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class Main2Fragment : Fragment() {
private lateinit var testArg: String
private lateinit var testArg2: String
companion object {
fun newInstance() = Main2Fragment()
}
@SuppressLint("SetTextI18n")
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View {
val view = inflater.inflate(R.layout.main2_fragment, container, false)
arguments?.let {
testArg = it["testArg"] as String
testArg2 = it["testArg2"] as String
}
var tvMain = view.findViewById<AppCompatTextView>(R.id.tv_main)
tvMain.text = "$testArg---$testArg2"
return view
}
}

我们发现传参是通过NavController 来传递的,具体源码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
NavController.java
/**
* Navigate to a destination from the current navigation graph. This supports both navigating
* via an {@link NavDestination#getAction(int) action} and directly navigating to a destination.
*
* @param resId an {@link NavDestination#getAction(int) action} id or a destination id to
* navigate to
* @param args arguments to pass to the destination
*/
public final void navigate(@IdRes int resId, @Nullable Bundle args) {
navigate(resId, args, null);
}

image

其实很好理解的,也就是我们以前所说的自定义URL使用Scheme方式来跳转传参

navigation.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
<navigation>
<activity
android:id="@+id/settings_activity"
android:name="com.wangjun.app.jetpacktodolist.ui.SettingActivity"
android:label="@string/activity_settings"
tools:layout="@layout/setting_activity" >
<!--深层链接-->
<deepLink app:uri="www.leonwang.com/hello/{testArg}" />
</activity>
</navigation>

AndroidManifest.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<activity
android:name=".ui.SettingActivity"
android:label="@string/activity_settings">
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data android:scheme="https"/>
<data android:scheme="http"/>
<data android:host="www.leonwang.com"/>
<data android:pathPrefix="/hello/"/>
</intent-filter>
</activity>
注意

根据官方文档说明,为了保证导航的正确使用,我们需要在目标的Activity中重写onSupportNavigateUp,以确保导航器能够正确的回退栈。

1
2
3
override fun onSupportNavigateUp(): Boolean {
return navController.navigateUp()
}

最后

好了,导航组件基本的使用就这么多,DEMO。关于更加详细的介绍,请参考官方文档说明