当前位置:网站首页>Navigation - are you sure you want to take a look at such an easy-to-use navigation framework?
Navigation - are you sure you want to take a look at such an easy-to-use navigation framework?
2022-07-07 14:35:00 【51CTO】
Preface
What is? Navigation? Official documents are a little difficult to understand . therefore , Here I would like to sum up with my own words , We're dealing with Fragment It is necessary to write Fragment To operate Fragment Of , and Navigation The emergence of is to solve some pain points we developed before .Navigation Mainly used to realize Fragment Instead of Activity Page navigation function , Give Way Fragment It can easily jump and pass parameters , We can do that by using Navigation, Give Way Fragment Instead of android Most of the projects Activity. But it should be noted that in use Navigation Switch the changes of page life cycle , Avoid stepping on pits in the development process .
Official documents :< https://developer.android.google.cn/jetpack/androidx/releases/navigation>
navigation Project address :< https://github.com/googlecodelabs/android-navigation>
this paper Demo Address :< https://github.com/taxze6/Jetpack_learn/tree/main/Jetpack_basic_learn/navigation>
Use Navigation What's the advantage ?
- Handle Fragment Business
- By default , Can correctly handle round-trip operations
- Provide standardized resources for animation and transformation
- Implement and handle deep links
- Including navigation interface mode , For example, drawer navigation bar and bottom navigation , We only need to complete a small amount of code
- Safe Args - Provides type safe navigation and data transfer between targets Gradle plug-in unit
- ViewModel Support - You can use ViewModel The scope of is limited to the navigation map , To share data related to the interface between the targets of the icon
How to use Navigation Well ?
Navigation At present, only AndroidStudio 3.2 Above version support , If your version is insufficient 3.2, please Download this The latest version AndroidStudio(2202 No one should still use it after years 3.2 The following version !)
Starting to learn Navigation
Before component , We need to be right first Navigation
Have a simple understanding of the main components ,Navigation It's made up of three parts :
- Navigation graph: One that contains all navigation related information
XML
resources - NavHostFragment: A special kind
Fragment
, Container used to hold navigation content - NavController: Manage application navigation objects , Realization
Fragment
Between the jump and other operations
Now let's start learning Navigation La
First step : Add dependency
The second step : Create a navigation map
① Right click on the res
Catalog , Then select New
→ Android Resource Directory
. The system displays New Resource Directory
Dialog box .Directory name
Enter your folder name ( It's usually navigation
),Resource type
choice navigation
② Right click navigation
Folder , then new
→Navigation Resource File
stay File name
Enter a name in ( Commonly used nav_graph_main or nav_graph)
The third step : establish Fragment
In order to enrich the jump , Here we create three
Fragment
We can create it manually :
FirstFragment:
Create two more and FirstFragement
Same :SecondFragment
,ThirdFragment
We can also pass Navigation graph
establish
We are building a new one nav_graph_main.xml
Next , Switch to... In the upper right corner Design
Pattern , And then in Navigation Editor
in , Click on Create new destination
, Choose what you need Fragment
after , Click on Finish
, You'll find out Fragment
It has appeared in the panel we can drag .
Step four : take Fragment Drag into the panel and configure the jump
Only need Navigation Editor
Double click the desired Fragment
It will be added to the panel .
Click on one of Fragment
, You'll find that , There will be a dot on his right , Drag the dot to point to the one you want to jump Fragment
, We set up FirstFragment
→ SecondFragment
→ ThirdFragment
→ FirstFragment
We will nav_graph_main.xml
Switch to Code
Next , Let's interpret xml
-
navigation
It's a label , adopt startDestination
Configure the first page launched by default , The configuration here is firstFragment
, We can change it manually in the code mainFragment
( The first one at startup Fragment), You can also click Fragment
, Click again Assign Start Destination
, You can also modify mainFragment
-
fragment
The label means this is a Fragment -
action
Tags define the behavior of page jumps , Each line in the above figure ,destination
Define the target page for jump , You can also add animation during jump
Be careful : stay fragment Label under android:name attribute , Whether the package name is correctly declared
Step five : Handle MainActivity
① edit MainActivity
Layout file for , Add in the layout file NavHostFragment
. We need to tell Navigation
and Activity
, our Fragment
Where is the show , therefore NavHostFragment
In fact, it is the container of the navigation interface
-
fragment
Label under android:name
Is used to designate NavHostFragment
-
app:navGraph
Is used to specify the Navigation view -
app:defaultNavHost=true
Every time Fragment
When switching , Save the click record in the stack , When you need to exit , After pressing the back key , You'll get it from the stack last time Fragment
Display . But in some cases , Such operation is not very friendly , But fortunately, we just need to app:defaultNavHost=true
Change it to app:defaultNavHost=false
Or delete this line . When it is false
Under the circumstances , No matter how you switch Fragment
, Click the back button again and exit directly app
. Of course, we can also listen to its stack , So as to achieve , Click the back button once to return to the home page , Click the back button again to exit app
.
② modify MainActivity
We rewrote onSupportNavigateUp
, That we will Activity
Of back
Click event delegation
Step six : Handle Fragment Corresponding jump event of
①Fragment
Layout : Give a button to jump , One TextView
Used to identify , Three Fragment
The layout is the same
② To configure Fragment Corresponding jump event
Among them R.id.action_firstFragment_to_secondFragment2
Such a sign , Is in nav_graph_main.xml
Of action
Configured under the label .
③ The final rendering :
Jump animation & Custom animation
We will find that , In the example just now , When we jump to the interface , There is no animation of sliding left and right into the interface , Looks very stiff , So we need to add animation to the jump process .
① Add default animation :
stay nav_graph_main.xml
In the document Design
In mode , Click to connect two Fragment
Line . Then you will find a Animations
The panel , And then we click enterAnim
The rightmost ellipse of these options , Then it pops up Pick a Resoure
The panel , We can choose the animation we need here , Here we set nav_default_enter_anim
. Empathy exitAnim
We also set an animation ,nav_default_exit_anim
. Then run the code and you will find a gradual jump animation . Then after configuring the animation, you will find action
More animation related attributes
-
enterAnim
: Animation of the target page when jumping -
exitAnim
: The original page animation when jumping -
popEnterAnim
: Animation of the target page when backing back -
popExitAnim
: Back to the original page animation
② Custom animation
There are many different jump animations in the real business requirements , The official default animation is not enough , So we should learn to customize animation .
⑴ establish Animation Resource file
Right click on the res
Catalog , Then select New
→ Android Resource File
. The system displays New Resource File
Dialog box .File name
Enter your folder name ( I'm going to set it to slide_from_left
),Resource type
choice Animation
, Then we can send it to res
There is one more... In the catalog anim
Catalog , There are our customized animations .
⑵ Write our animation code
Here are some common examples :
Common properties :
attribute | Introduce |
alpha | Transparency setting effect |
scale | Size scaling effect |
rotate | Rotation effect |
translate | Displacement effect |
Common settings :
attribute | Introduce |
android:duration | Animation duration |
fromXX | Start state |
toXX | End state |
⑶ Use custom animation files
Using custom animation is the same as using default animation .
Rotation effect :
How to pass data ?
Navigation Enables you to attach data to navigation operations by defining destination parameters . In general , It is recommended to pass a small amount of data . For example, passing userId, Rather than specific user information . If you need to transfer a lot of data , Still recommended ViewModel.
stay nav_graph_main.xml
In the document Design
In mode . Click to select Fragment
. On the right side of the Attributes
The palette , Click on Arguments
The plus sign to the right of the option . Add the required parameters . After adding parameters , In the arrow Action
Click on , It will be on the right Argument Default Values
Show this in userId
Variable , stay xml You can also see that
Code processing :
Transfer data dynamically
① We can use Bundle Pass parameters between destinations
② Then we can accept the parameters
In the corresponding Fragment:
stay Activity Use setGraph Switch between different Navigation
Usually , We are more than one
navigation
The file of , We need to decide which one to use according to the business situation , Here we can use our setGraph
To switch between different Navigation
了 .
① hold activity_main
in fragment
Label under app:navGraph
This attribute is removed
② In the code through setGraph
Set up app:navGraph
Here we are , We're done Navigation
Most usage , Here are some important points , And learn and summarize this article through a case .
NavController
We have already talked about
Navigation
Use , Processing Fragment
When the corresponding jump event of , We used findNavController
This method , Actually , This is Navigation
Of the three parts of NavController
One of them api
. So what is NavController
Well ? It is responsible for operation Navigation
Under the framework of Fragment
Jump and exit 、 Animation 、 Monitor the current Fragment
Information , Of course, these are basic operations . Because except in Fragment
Call in , In practice, it can also be used in Activity Call in . If you can use it flexibly , It can help you realize any form of page Jump , You can also use TabLayout
coordination Navigation
Page design on the homepage .
How to get NavController
What's the example? ?
In the previous basic use, we also used .
Navigation Common operations :
①popBackStack eject Fragment
Now let's start with
oneFragment
Jump to secondFragment
On the way to thirdFragment
, Then we want to start from thirdFragment
go back to secondFragment
You can use it there popBackStack
② Pop up to the specified Fragment
Is also used popBackStack
, This method can Realize the need to empty the intermediate navigation stack .
③navigateUp() Up Navigation
navigateUp
It is also the execution return to the upper level Fragment
The function of . and popBackStack
Function as . Then since it exists, it must have its special place .navigateUp
The function of upward return is actually a call popBackStack
Of . however ,navigateUp
There is a layer of judgment in the source code of , Judge this Navigation
Is it the last Fragment
. Use popBackStack()
If the current return stack is empty, an error will be reported , Because the stack is empty ,navigateUp()
Will not be , Or stay in the current interface .
④ Add navigation monitoring
⑤ Get the current navigation destination
Use getCurrentDestination
You can get the current navigation destination
⑥ Judge what is displayed on the current page Fragment Is it a goal Fragment
Use Safe Args Make sure the type is safe
Through the top NavController We can do it fragment Jump between , however Google It is recommended to use Safe Args Gradle Plug-in implementation . This plug-in can generate simple objects and builder classes , These classes can safely navigate and pass parameters between destinations .
that , How to use Safe Args
Well .
① In the outermost part of the project build.gradle
Add
② stay app
、module
Under the build.gradle
Join in
If you need to generate a for Java
Module or Java
and Kotlin
Of hybrid modules Java
The language code
If you need to generate a for Kotlin
Unique module Kotlin
Code , Please add the following line :
To use Safe Args, Must be in gradle.properties Add to this file
android.useAndroidX=true android.enableJetifier=true
In order to avoid the generated class name and method name being too complex , The navigation map needs to be adjusted , Revised action Of id, Because of the auto generated id Is too long. , The class name and method name generated by the plug-in are also very long .
Then it will generate BlankFragment
and BlankFragment2
Class of , Then it can be used as above , Pass parameters .
You can also use set Method Assign values to the corresponding parameters
adopt Navigation imitation WeChat Bottom jump
adopt Navigation Realize the super common bottom jump function in development
Don't talk much , First on the renderings :
① Right click on the res
Catalog , Then select New
→ Android Resource File
. The system displays New Resource File
Dialog box .File name
Enter your folder name ( I'm going to set it to menu
),Resource type
choice Menu
, Then we can send it to res
There is one more... In the catalog menu
Catalog , Inside is our bottom jump item
.
② Get into menu.xml
Of Design
Next
Fill in four Item
, And set it separately id
,title
,icon
③ Create four Fragment
, And in Navigation
Build links in
Fragment The layout of the is very simple , Here is a code .
stay nav_graph_main.xml
Establishing a connection , Pay attention to each of these Fragment
Of id
Want to be with menu.xml
Medium id
One-to-one correspondence
④ stay activity_main
Use in BottomNavigationView
Create a bottom jump
Here it is drawable
Next create a selector_menu_text_color.xml
Used to distinguish the current Item
⑤ stay MainActivty Set the switching logic
In this way, we can achieve the effect in the rendering , Specific code can be viewed Git
Warehouse
Epilogue
This article has been described in great detail Jetpack Navigation Most uses of , But after reading the article , You still need to practice more , I believe you will soon master Navigation La Because my ability is limited , If there is something wrong with the article, you are welcome to point out , If you have any questions, please leave a message in the comment area to discuss ~
About me
Hello, I am a Taxze, If you think the article is valuable to you , I hope you can point to my article ️, You are welcome to pay attention to my Blog .
If you think the article is not good enough , Please also go through Focus on Urge me to write better articles —— In case I improve one day ?
Foundation Series :
2022 · Let me show you Jetpack Architecture components go from beginner to proficient — Lifecycle
When you really learn DataBinding after , You'll find that “ This thing smells good ”!
Navigation — Are you sure you don't want to take a look at such a useful jump management framework ?( this paper )
The following parts are still codewords , Hurry to order a collection
2022 · Let me show you Jetpack Architecture components go from beginner to proficient — Room
2022 · Let me show you Jetpack Architecture components go from beginner to proficient — Paging3
2022 · Let me show you Jetpack Architecture components go from beginner to proficient — WorkManager
2022 · Let me show you Jetpack Architecture components go from beginner to proficient — ViewPager2
2022 · Let me show you Jetpack Architecture components go from beginner to proficient — Login to the registration page (MVVM)
Advanced Series :
coroutines + Retrofit Network request status encapsulation
Room Cache encapsulation
.....
边栏推荐
- PLC:自动纠正数据集噪声,来洗洗数据集吧 | ICLR 2021 Spotlight
- Applet directory structure
- 拼多多败诉,砍价始终差0.9%一案宣判;微信内测同一手机号可注册两个账号功能;2022年度菲尔兹奖公布|极客头条...
- leetcode:648. 单词替换【字典树板子 + 寻找若干前缀中的最短符合前缀】
- 【历史上的今天】7 月 7 日:C# 发布;Chrome OS 问世;《仙剑奇侠传》发行
- gvim【三】【_vimrc配置】
- 2022 cloud consulting technology series high availability special sharing meeting
- Es log error appreciation -maximum shards open
- WPF DataGrid realizes the UI interface to respond to a data change in a single line
- PERT图(工程网络图)
猜你喜欢
Base64 encoding
MicTR01 Tester 振弦采集模塊開發套件使用說明
Selenium Library
AWS学习笔记(三)
用例图
libSGM的horizontal_path_aggregation程序解读
什么是云原生?这回终于能搞明白了!
The longest ascending subsequence model acwing 482 Chorus formation
UML 顺序图(时序图)
Instructions d'utilisation de la trousse de développement du module d'acquisition d'accord du testeur mictr01
随机推荐
属性关键字ServerOnly,SqlColumnNumber,SqlComputeCode,SqlComputed
UML 顺序图(时序图)
Leetcode——344. Reverse string /541 Invert string ii/151 Reverse the word / Sword finger in the string offer 58 - ii Rotate string left
用例图
Pert diagram (engineering network diagram)
The world's first risc-v notebook computer is on pre-sale, which is designed for the meta universe!
bashrc与profile
常用数字信号编码之反向不归零码码、曼彻斯特编码、差分曼彻斯特编码
Pytorch model trains practical skills and breaks through the bottleneck of speed
electron remote 报错
The longest ascending subsequence model acwing 482 Chorus formation
多商戶商城系統功能拆解01講-產品架構
Multi merchant mall system function disassembly lecture 01 - Product Architecture
The longest ascending subsequence model acwing 1014 Mountaineering
全球首款 RISC-V 笔记本电脑开启预售,专为元宇宙而生!
Codes de non - retour à zéro inversés, codes Manchester et codes Manchester différentiels couramment utilisés pour le codage des signaux numériques
VSCode 配置使用 PyLint 语法检查器
Mmkv use and principle
Full details of efficientnet model
PLC: automatically correct the data set noise, wash the data set | ICLR 2021 spotlight