Android jetpack(Navigation篇)
看到网上很对人吐槽navigation如何多余,以及在xml里面编写大量代码,不利于阅读等,其实对于习惯用代码处理逻辑的我来说,确实觉得不怎么方便,但是我总觉得谷歌有着自己的宏伟目标,那就是可视化编程,看着后面推出来的ConstraintLayout以及navigation,DataBinding等,都在可视化编程上给了更多的便利。总之,存在即合理。用不到也要学习学习。所以做个笔记。
使用
使用的时候可以遵循这个顺序,建立需要的Fragment-》建立NavigationGraph并建立跳转链接-》activity中建立NaviHost-》NavController的调用
所以我们先建立两个Fragment我这里就用HomeFragment、DetailFragment示意,在这两个Fragment中都有一个按钮,HomeFragment的按钮点击跳转到DetailFragment,DetailFragment的按钮点击回到HomeFragment。当然我们暂时先把button写出来即可,点击跳转等NavController绑定后填写。
他们的布局如下:
fragment_home.xml
<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=".navigation.HomeFragment">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="66dp"
android:text="跳转"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
fragment_detail.xml
<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=".navigation.DetailFragment">
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="返回"
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。在res下新建navigation文件夹,并建立一个要用的graph文件
image.png
当点击新建时会提示需要引入资源,点击ok即可。
image.png
找到刚刚新建的graph文件,选择design模式。
image.png
点击添加Fragment
image.png
使用箭头配置跳转关系
image.png
然后他就能自动帮我们编写代码,最后生成的xml如下:
my_navi_graph.xml
<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/my_navi_graph"
app:startDestination="@id/homeFragment">
<fragment
android:id="@+id/homeFragment"
android:name="com.example.myapplication.navigation.HomeFragment"
android:label="fragment_home"
tools:layout="@layout/fragment_home" >
<action
android:id="@+id/action_homeFragment_to_detailFragment"
app:destination="@id/detailFragment" />
</fragment>
<fragment
android:id="@+id/detailFragment"
android:name="com.example.myapplication.navigation.DetailFragment"
android:label="fragment_detail"
tools:layout="@layout/fragment_detail" >
<action
android:id="@+id/action_detailFragment_to_homeFragment"
app:destination="@id/homeFragment" />
</fragment>
</navigation>
然后activity中建立Navigation容器。
找到activity布局,还是用design模式,搜索框内找到NavHostFragment,拖拽一个NavHostFragment到下面的约束布局中,并撑满全屏。
image.png
然后会让你选择一个graph,我们就选择刚刚新建的即可
image.png
最终activity的布局代码如下:
activity_navigation.xml
<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=".navigation.NavigationActivity">
<fragment
android:id="@+id/fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:navGraph="@navigation/my_navi_graph" />
</androidx.constraintlayout.widget.ConstraintLayout>
最后我们在activity中绑定上我们的控制器,
public class NavigationActivity extends AppCompatActivity {
private NavController mNavController;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation);
mNavController = Navigation.findNavController(this, R.id.fragment);
NavigationUI.setupActionBarWithNavController(this,mNavController);
}
}
然后就可以设置fragment的点击事件了。
HomeFragment
public class HomeFragment extends Fragment {
public static HomeFragment newInstance() {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
NavController navController = Navigation.findNavController(v);
navController.navigate(R.id.action_homeFragment_to_detailFragment);
}
});
}
}
DetailFragment
public class DetailFragment extends Fragment {
public static DetailFragment newInstance() {
DetailFragment fragment = new DetailFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_detail, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
NavController navController = Navigation.findNavController(v);
navController.navigate(R.id.action_detailFragment_to_homeFragment);
}
});
}
}
这样,我们的跳转就算完成了,但是进入DetailFragment 后 actionbar上的返回按钮不能返回到HomeFragment了,原因是我们应该告诉actionbar原来的机制,我们的逻辑由navigation控制了,你们不用操心了,只要在activity中复写onSupportNavigateUp即可
public class NavigationActivity extends AppCompatActivity {
private NavController mNavController;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation);
mNavController = Navigation.findNavController(this, R.id.fragment);
NavigationUI.setupActionBarWithNavController(this,mNavController);
}
@Override
public boolean onSupportNavigateUp() {
return mNavController.navigateUp() || super.onSupportNavigateUp();
}
}
跳转动画
选择graph文件,使用design模式,点击你想要添加动画的跳转箭头那根线,右边的Animations就有我们需要的进场动画当然支持自定义也支持默认动画。
image.png
设置完成后,xml代码就会自定生成
image.png
传值
传统的fragment传值是通过Bundle传值,他存在明显的缺点,比如A传值给B,B在接收的时候必须知道A传过来的KEY和值得数据类型,不然就会报错。而Navigation对此也进行了修改。
Navigation传值需要引入插件,在整个工程的gradle中引入 classpath 'androidx.navigation:navigation-safe-args-gradle-plugin:2.3.0-alpha06' 如图:
image.png
然后在需要的model中的gradle引入apply plugin: 'androidx.navigation.safeargs'
image.png
然后我们找到graph文件,在需要的地方加上传值
image.png
<argument android:name="user_name"
app:argType="string"
android:defaultValue=""/>
<argument android:name="age"
app:argType="integer"
android:defaultValue="0"/>
然后build一下工程,插件会生成一些代码。
我们是添加在Home跳Detail的跳转中,所以我们在Home的按钮点击实践中传入值。
image.png
public class HomeFragment extends Fragment {
public static HomeFragment newInstance() {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Bundle bundle = new HomeFragmentArgs.Builder()
.setUserName("yanjin")
.setAge(25).build().toBundle();
NavController navController = Navigation.findNavController(v);
navController.navigate(R.id.action_homeFragment_to_detailFragment,bundle);
}
});
}
}
在DetailFragment取值。
public class DetailFragment extends Fragment {
public static DetailFragment newInstance() {
DetailFragment fragment = new DetailFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(getArguments() != null){
HomeFragmentArgs fragmentArgs = HomeFragmentArgs.fromBundle(getArguments());
String userName = fragmentArgs.getUserName();
int age = fragmentArgs.getAge();
Log.d("yanjin","userName = "+userName +" age ="+age);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_detail, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
NavController navController = Navigation.findNavController(v);
navController.navigate(R.id.action_detailFragment_to_homeFragment);
}
});
}
}
NavigationUI
NavigationUI是为了方便管理actionBar引入的。比如我们在Home的actionBar上面加入一个menu,点击跳转到Detail中,涉及到actionBar就能用到NavigationUI。
新建一个menu
image.png
menu_settings.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/detailFragment"
android:icon="@mipmap/ic_launcher"
android:title="跳转到detail"/>
</menu>
记住这里的android:id="@+id/detailFragment"一定和graph里面的id一致,跳哪个页面填哪个。
然后activity中设置appbar
public class NavigationActivity extends AppCompatActivity {
private NavController mNavController;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation);
mNavController = Navigation.findNavController(this, R.id.fragment);
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(mNavController.getGraph()).build();
NavigationUI.setupActionBarWithNavController(this,mNavController,appBarConfiguration);
}
@Override
public boolean onSupportNavigateUp() {
return mNavController.navigateUp() || super.onSupportNavigateUp();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.menu_settings,menu);
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
return NavigationUI.onNavDestinationSelected(item,mNavController) || super.onOptionsItemSelected(item);
}
}
深层链接之PendingIntent
在开发中,我们可能需要点击通知跳转到一个activity下的第N个fragment,所以就用到PendingIntent,Navigation刚好支持在activity中的多个fragment中显示第N个,所以,我们来举个例子。
我们在HomeFragment中点击一个按钮出现通知,点击通知跳转到DetailFragment。
首先home的布局添加一个按钮
<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=".navigation.HomeFragment">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="66dp"
android:text="跳转"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="弹出通知"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
然后点击按钮后提示弹窗并且按钮notify绑定pendingIntent
public class HomeFragment extends Fragment {
private int notificationID;
public static HomeFragment newInstance() {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Bundle bundle = new HomeFragmentArgs.Builder()
.setUserName("yanjin")
.setAge(25).build().toBundle();
NavController navController = Navigation.findNavController(v);
navController.navigate(R.id.action_homeFragment_to_detailFragment,bundle);
}
});
view.findViewById(R.id.button3).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
customNotify();
}
});
}
private void customNotify() {
//26以上需要渠道
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
NotificationChannel channel = new NotificationChannel(getActivity().getPackageName(),"MyChannel", NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("My NotificationChannel");
NotificationManager notificationManager = getActivity().getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
Notification notification = new NotificationCompat.Builder(getActivity(), getActivity().getPackageName())
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Deep Link")
.setContentText("点击跳转")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(getPendingIntent()).build();
NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(getActivity());
notificationManagerCompat.notify(notificationID++,notification);
}
private PendingIntent getPendingIntent() {
return Navigation.findNavController(getActivity(),R.id.button)
.createDeepLink()
.setGraph(R.navigation.my_navi_graph)
.setDestination(R.id.detailFragment)
.createPendingIntent();
}
}