android使用Navigation实现Fragment之间的跳转之二:参数传递
参数传递
- 1.在nav_graph中新建一个destinations
- 2.双击右侧Arguments按钮,添加一个或多个参数
- 3.按回车键完成,打开text视图:
图一
在HomeDestinations中可以这样写:
Bundle bundle = new Bundle();bundle.putInt("argument", 100);Navigation.findNavController(v).navigate(R.id.action_firstFragment_to_forthFragment,bundle);
在Fragment中这样接收:
mTextView = (TextView) view.findViewById(R.id.text_view);mTextView.append(getArguments().getInt("argument")+"");
运行:
图二
类型安全的方式参数传递:
还有一种类型安全的传递数据的方法,首先在项目的build.gradle添加依赖:
repositories { google() jcenter() } dependencies { classpath "android.arch.navigation:navigation-safe-args-gradle-plugin:1.0.0-alpha01" }
在app的build.gradle添加:
apply plugin: 'com.android.application'apply plugin: 'androidx.navigation.safeargs'
然后在在nav_graph中新建一个destinations,并添加参数
注意:
在使用safeargs插件生成代码时,分为发送方和接收方两个类,发送方命名为<类名>+"Directions",
接受方命名为<类名>+"Args",action会成为一个方法(如此处是从FirstFragment跳转到ForthFragment,发送方命名为<FirstFragmentDirections>,接收方命名为<ForthFragmentArgs>,action:action_firstFragment_to_forthFragment会成为:FirstFragmentDirections.action_firstFragment_to_forthFragment())
在发送方(FirstFragment)写:
FirstFragmentDirections.Action_firstFragment_to_forthFragment action = FirstFragmentDirections.action_firstFragment_to_forthFragment();action.setArgument(99);Navigation.findNavController(v).navigate(action);
接收方(ForthFragment)写:
mTextView = (TextView) view.findViewById(R.id.text_view);int argument = ForthFragmentArgs.fromBundle(getArguments()).getArgument();mTextView.append(argument+"");
运行:
图三
Navigation嵌套
右键单击一个destination,选择Move to Nested Graph > New Graph:
image.png
xml视图:
<?xml version="1.0" encoding="utf-8"?>
跳转还是一样的:
Navigation.findNavController(v).navigate(R.id.action_firstFragment_to_forthFragment);
运行:
图四
DeepLine:
类似于activity的隐式跳转:
- 1.点击一个destination,单机右侧菜单DeepLine选项:
图无
添加一个uri,此处为:"https://www.king.com"
此时:
!图六](https://upload-images.jianshu.io/upload_images/3304172-e64d9e2b3bbcfb57.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/400)
xml视图:
- 2.添加到activity:
需要AndroidStudio3.2+,打开清单文件,添加:
- 3.使用:
Intent intent = new Intent();intent.setData(Uri.parse("https://www.king.com"));NavController navController = Navigation.findNavController(v);navController.onHandleDeepLink(intent);
切换动画:
点击箭头:
图七
编辑右侧属性列表 transitions,有四种动画,均支持自定义动画:
- enter: A的进入动画
- exit: A的退出动画
- Pop enter:B的进入动画
- Pop exit: B的退出动画
设置完毕后,xml视图:
更多相关文章
- android 手势屏幕平移图片转换效果(也可以平移文本)
- Android 如何更换屏幕上锁界面背景图片
- 管理图片缓存
- android 图片透明
- Android动画效果translate、scale、alpha、rotate详解
- Android实现图片轮播
- Android图片左右切换和拖动大小