JetPack--Navigation
目前UI一般使用Activity嵌套使用Fragment的方式,但是Fragment的管理是比较繁琐的,需要手动通过FragmentManager和FragmentTransaction来管理Fragment的切换。以及切换动画、参数传递、AppBar的管理等。
JetPack提供了一个工具:Navigation,封装了Fragment的一系列操作,Navigation分为三个组件:
1.Navigation Graph:一种xml资源文件,包含应用程序所有的页面,以及页面间的关系
2.NavHostFragment:一个特殊的Fragment,可以将它看作是其他Fragment的容器,Navigation Graph中Fragment正是使用NavHostFragment进行展示的
3.NavController:用于在代码中完成Navigation Graph中具体的页面切换工作
当想要切换Fragment时,使用NavController对象,指定跳转Navigation Graph中哪个Fragment,那么NavHostFragment会切换成相应的Fragment
一、初识Navigtion
1.Navigtion上手
首先创建两个Fragment:HomeFragment和DetailFragment
布局文件是相同的:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".HomeFragment">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".DetailFragment">
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
创建NavigationGraph,如果是第一次创建,会提示是否导入依赖,我们选择是就可以了
根据下图提示的先导入Fragment,再建立连接关系:
在Activity布局文件中使用NavHostFragment:
xml如下,使用的是fragment标签:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<fragment
android:id="@+id/fragmentContainerView"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:navGraph="@navigation/my_navigation_graph" />
</androidx.constraintlayout.widget.ConstraintLayout>
Activity代码中,获取NavController对象,并绑定ActionBar
package com.aruba.navigation;
import androidx.appcompat.app.AppCompatActivity;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.NavigationUI;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
private NavController navController;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取NavController对象
navController = Navigation.findNavController(this, R.id.fragmentContainerView);
//将ActionBar与NavController绑定
NavigationUI.setupActionBarWithNavController(this, navController);
}
}
在fragment中设置一个点击事件,使用NavController进行fragment跳转,通过内部任意一个View就能获取NavController对象
HomeFragment
package com.aruba.navigation;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class HomeFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_home, container, false);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
View button = getView().findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Activity中绑定后,可以通过内部任意一个View获取NavController对象
NavController navController = Navigation.findNavController(view);
//指定跳转的fragment,即navigation graph中的action
navController.navigate(R.id.action_homeFragment_to_detailFragment);
}
});
}
}
DetailFragment
package com.aruba.navigation;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class DetailFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_detail, container, false);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
View button = getView().findViewById(R.id.button2);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Activity中绑定后,可以通过内部任意一个View获取NavController对象
NavController navController = Navigation.findNavController(view);
//指定跳转的fragment,即navigation graph中的action
navController.navigate(R.id.action_detailFragment_to_homeFragment);
}
});
}
}
最后在Activity中添加ActionBar返回键支持:
@Override
public boolean onSupportNavigateUp() {
return navController.navigateUp();
}
2.跳转动画
添加Fragment的跳转动画比较简单,只需要在NavigationGraph中的action添加即可
image.png
3.参数传递
NavController的navigate方法可以传递一个bundle,接受的Fragment和以前一样可以用getArguments方法获取:
//Activity中绑定后,可以通过内部任意一个View获取NavController对象
NavController navController = Navigation.findNavController(view);
Bundle bundle = new Bundle();
bundle.putString("name", "张三");
//指定跳转的fragment,即navigation graph中的action
navController.navigate(R.id.action_homeFragment_to_detailFragment, bundle);
还可以使用插件的方式:
在主工程的Gradle中添加依赖
dependencies {
classpath "com.android.tools.build:gradle:7.0.2"
classpath "androidx.navigation:navigation-safe-args-gradle-plugin:2.3.5"
}
在module中使用插件
plugins {
id 'com.android.application'
id 'androidx.navigation.safeargs'
}
我们就可以在NavigationGraph中定义参数了
xml中定义好后,在fragment跳转时使用
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Activity中绑定后,可以通过内部任意一个View获取NavController对象
NavController navController = Navigation.findNavController(view);
// Bundle bundle = new Bundle();
// bundle.putString("name", "张三");
HomeFragmentArgs build = new HomeFragmentArgs.Builder()
.setName("张三")
.setAge(1)
.build();
//指定跳转的fragment,即navigation graph中的action
navController.navigate(R.id.action_homeFragment_to_detailFragment, build.toBundle());
}
});
接收的fragment代码如下:
HomeFragmentArgs homeFragmentArgs = HomeFragmentArgs.fromBundle(getArguments());
Toast.makeText(getActivity(),
homeFragmentArgs.getName() + homeFragmentArgs.getAge(),
Toast.LENGTH_SHORT).show();
二、NavigationUI
Fragment的切换,除了Fragment页面本身的切换,通常还伴有AppBar的变化。为了方便管理,Navigation引入NavigationUI
创建完Fragment后,先创建NavigationGraph
<?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"
android:id="@+id/navigation_graph"
app:startDestination="@id/mainFragment">
<fragment
android:id="@+id/mainFragment"
android:name="com.aruba.navigation2.MainFragment"
android:label="fragment_main"
tools:layout="@layout/fragment_main" />
<fragment
android:id="@+id/settingFragment"
android:name="com.aruba.navigation2.SettingFragment"
android:label="fragment_setting"
tools:layout="@layout/fragment_setting" />
</navigation>
再创建menu,其中item的id指定为:NavigationGraph中对应fragment的id
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/settingFragment"
android:icon="@drawable/ic_launcher_background"
android:title="设置" />
</menu>
Activity中,先重写onCreateOptionsMenu方法,使用我们定义的menu,然后在onCreate中调用NavigationUI的setupActionBarWithNavController方法,其中多传入一个AppBarConfiguration对象,最后重写onOptionsItemSelected方法
package com.aruba.navigation2;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
private NavController navController;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
navController = Navigation.findNavController(this, R.id.fragmentContainerView);
AppBarConfiguration configuration = new AppBarConfiguration
.Builder(navController.getGraph())
.build();
NavigationUI.setupActionBarWithNavController(this, navController, configuration);
}
@Override
public boolean onSupportNavigateUp() {
return navController.navigateUp();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.item_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
return NavigationUI.onNavDestinationSelected(item, navController) ||
super.onOptionsItemSelected(item);
}
}
仔细看我们的效果,跳转到设置后,AppBar右上角的选项还在,那么我们需要在设置界面时,去除选项
在SettingFragment中,重写onCreateOptionsMenu方法,调用menu.clear(),并在onCreateView方法中调用setHasOptionsMenu(true)来确保onCreateOptionsMenu的执行
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_setting, container, false);
}
@Override
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
menu.clear();
super.onCreateOptionsMenu(menu, inflater);
}
效果:
如果你需要监听切换页面,那么对NavController添加切换监听
navController.addOnDestinationChangedListener(new NavController.OnDestinationChangedListener() {
@Override
public void onDestinationChanged(@NonNull NavController controller, @NonNull NavDestination destination, @Nullable Bundle arguments) {
}
});
三、DeepLink
Navigation可以生成通知点击的PendingIntent,用来直接跳转到Fragment,并支持参数传递
public PendingIntent getPendingIntent() {
Bundle bundle = new Bundle();
bundle.putString("name", "张三");
return Navigation.findNavController(this, R.id.fragmentContainerView)
.createDeepLink()
.setArguments(bundle)
.setGraph(R.navigation.navigation_graph)
.setDestination(R.id.settingFragment)
.createPendingIntent();
}
URI方式也是支持的
在NavigationGraph中使用deepLink标签,params可以以参数传递的方式获取:
<fragment
android:id="@+id/settingFragment"
android:name="com.aruba.navigation2.SettingFragment"
android:label="fragment_setting"
tools:layout="@layout/fragment_setting" >
<deepLink app:uri="www.aruba.com/{params}"/>
</fragment>
Manifest.xml中的指定nav-graph:
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<nav-graph android:value="@navigation/navigation_graph"/>
</activity>