current position:Home>Talk about "single activity + multiple fragments" mode
Talk about "single activity + multiple fragments" mode
2022-01-27 03:50:48 【xlu1997】
This should be MVVM The third article on the development framework , The first two articles can be viewed :
Write a MVVM Rapid development framework ( One ) Basic class encapsulation
Write a MVVM Rapid development framework ( Two ) Component transformation
single Activity+ many Fragment Pattern
Since I know this move, I'm basically reluctant to use activity 了 ,fragment You can quickly create and manage , Can reasonably design page Jump , Design Cool jump animation , Some operations can be managed uniformly .
- use Fragment replace Activity
In the past, most of the time will be Activity As a page ,Fragment As a sub page in the page ( It was called debris ), Basically, most functions consist of activity Realization , For example, the old version of Taobao app There are hundreds activity, Caton didn't want it at that time . With technology iterations , We found that activtiy establish 、 Switch 、 Destruction consumes far more performance than fragment Be big ,fragment Now it can also replace activity Implement most of the functions .
- take Activity As a container
I understand. single Activity+ many Fragment
A pattern does not mean a App There must be only one activity, For some business-related scenarios , Can be integrated into one single Activity+ many Fragment
modular , take activity As fragment The container of , Give Way fragment To do UI Drawing work .
- management Fragment Stack
We can use navigation management fragment,fragment Jump between 、 Stack management is easy ,navigation You can also animate the switch 、 Data transfer between pages .
Navigation Components
Navigation yes Jetpack One of the components , A long time ago iOS That's the way you jump , I was thinking Android Why not , It didn't take long Navigation It's coming out .
Navigation It can be understood as a management fragment The container of , In the container fragment Can achieve any jump ,
Based on using :
- We need to create... In the layout Fragment Containers :
<androidx.fragment.app.FragmentContainerView
android:id="@+id/main_fragment_container"
android:layout_width="match_parent"
android:layout_height="0dp"
android:name="androidx.navigation.fragment.NavHostFragment"
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/nav_main"/>
Copy code
- establish navigation.xml file
<?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_main"
app:startDestination="@+id/mainFragment">
<fragment
android:id="@+id/mainFragment"
android:name="com.example.mvvm_develop.MainFragment"
android:label="MainFragment" />
</navigation>
Copy code
- Use NavController
val navController = (childFragmentManager.findFragmentById(R.id.module_fragment_container) as NavHostFragment).navController
// Jump
navController.navigate(R.id.mainFragment)
Copy code
Some specific parameters and usage :
navGraph
This value points to xml file , stay xml In the document we can define fragment, Jump behavior , Destination, etc .
establish 、 newly added Fragment:
Create jump behavior :
Animation 、 Destination 、 Returns the stack configuration :
NavController
It literally means navigation controller ,NavController You can control the jump 、 return 、 Animation 、 Monitor and other operations . We can use it for flexible jumps ,Google There are also some Navigation Demo Demonstrate how to cooperate with Toolbar And the bottom navigation bar .
I won't explain the specific usage here , There are many articles , You can also refer to Official website .
Navigation The problem is :
Go back to the life cycle
Navigation At present, there is a problem :Fragment Go back and walk the life cycle , The question may be Google Want to make Fragment and activity Have the same working mode , It's really annoying to walk a single life cycle , We can customize it NavHostFragment To fix this problem , Specific reference Project code
After modification, use the following :
android:name="androidx.navigation.fragment.NavHostFragment"
Modify it to our custom NavHostFragment:
android:name="com.example.baselibrary.navigation.NavHostFragment"
<fragment
android:id="@+id/navigation_main"
android:name="com.example.baselibrary.navigation.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:navGraph="@navigation/nav_main"/>
Copy code
Used in componentization Navigation
We usually use the bottom navigation bar to app Divide different functions , These are all separate module, But in navigation How to proceed in module The jump between ?
such as :
Its layout file is a FragmentContainerView
+BottomNavigationView
, When switching the following buttons, you need to switch to different moduel page . First, we'll look at different moduel Think of it as a “ single activity+ many fragment” Module , Or you can omit activity.
Mode one :
google Of demo It's in MainActivity Create a main_navGraph, It contains different sub moduel Of navGraph , as follows :
<?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"
android:id="@+id/nav_module"
app:startDestination="@+id/navi_home">
<include app:graph="@navigation/navi_home"/>
<include app:graph="@navigation/navi_collection"/>
<include app:graph="@navigation/navi_center"/>
</navigation>
Copy code
navi_home
、navi_collection
、navi_center
Son moduel Medium navGraph file , This practice requires it to specify startDestination
, And can only jump to startDestination
coordination BottomNavigationView
Use :
val navController = (childFragmentManager.findFragmentById(R.id.module_fragment_container) as NavHostFragment).navController
setupWithNavController(binding.bottomNav,navController)
Copy code
In this way, we can really achieve moduel Switch between , But I found that this method switches every time naviagtion Will be reinitialized , This leads to high performance consumption .
Maybe I use the wrong posture ?
Mode two :
because app module Itself is dependent on each child moduel Of , We can do it in navGraph Direct use of sub moduel Medium Fragment, The main page only needs to add each module The Lord of Fragment That's it :
<?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"
android:id="@+id/nav_module"
app:startDestination="@+id/navi_home">
<fragment
android:id="@+id/navi_home"
android:name="com.xlu.module_tab1.HomeFragment"
android:label="HomeFragment" />
<fragment
android:id="@+id/navi_collection"
android:name="com.xlu.module_collection.FragmentCollection"
android:label="CenterFragment" />
<fragment
android:id="@+id/navi_center"
android:name="com.xlu.module_center.CenterFragment"
android:label="FragmentCollection" />
</navigation>
Copy code
Switch directly when switching the bottom state Fragment That's it :
val navController = (childFragmentManager.findFragmentById(R.id.module_fragment_container) as NavHostFragment).navController
binding.bottomNav.setOnItemSelectedListener(object :NavigationBarView.OnItemSelectedListener{
override fun onNavigationItemSelected(item: MenuItem): Boolean {
navController.navigate(item.itemId)
return true
}
})
Copy code
If you are lazy, you can BottomNavigationView The use of menu Medium id And navGraph Set it to the same ah ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha
Basically ARouter+Navigation It can meet most of the page Jump needs , But there are still some difficulties , It's just different moduel Between navGraph How to control each other , I haven't thought of a good solution for the time being ( It can be implemented by providing interface services through the above-mentioned alternatives ), After all Navigation I'm not going to prepare for componentization .
The last attached mvvm_develop Project address , Humble Androider Online search star
copyright notice
author[xlu1997],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201270350428969.html
The sidebar is recommended
- Spring IOC container loading process
- [thinking] the difference between singleton mode and static method - object-oriented programming
- Hadoop environment setup (MySQL environment configuration)
- 10 minutes, using node JS creates a real-time early warning system for bad weather!
- Git tool
- Force deduction algorithm - 92 Reverse linked list II
- What is the sub problem of dynamic programming?
- C / C + +: static keyword summary
- Idea does not have the artifacts option when configuring Tomcat
- Anaconda can't open it
guess what you like
-
I don't know how to start this
-
Matlab simulation of transportation optimization algorithm based on PSO
-
MySQL slow log optimization
-
[Vue] as the window is stretched (larger, smaller, wider and higher), the text will not be displayed
-
Popular Linux distributions for embedded computing
-
Suzhou computer research
-
After installing SSL Certificate in Windows + tomcat, the domain name request is not successful. Please answer!!
-
Implementation time output and greetings of jQuery instance
-
The 72 year old uncle became popular. Wu Jing and Guo fan made his story into a film, which made countless dreamers blush
-
How to save computer research
Random recommended
- Springboot implements excel import and export, which is easy to use, and poi can be thrown away
- The final examination subjects of a class are mathematical programming, and the scores are sorted and output from high to low
- Two pronged approach, Tsinghua Professor Pro code JDK and hotspot source code notes, one-time learning to understand
- C + + recursive knapsack problem
- The use of GIT and GitHub and the latest git tutorial are easy to understand -- Video notes of crazy God speaking
- PostgreSQL statement query
- Ignition database test
- Context didn't understand why he got a high salary?, Nginxfair principle
- Bootstrap switch switch control user's guide, springcloud actual combat video
- A list that contains only strings. What other search methods can be used except sequential search
- [matlab path planning] multi ant colony algorithm grid map path planning [including GUI source code 650]
- [matlab path planning] improved genetic algorithm grid map path planning [including source code phase 525]
- Iinternet network path management system
- Appium settings app is not running after 5000ms
- Reactnative foundation - 07 (background image, status bar, statusbar)
- Reactnative foundation - 04 (custom rpx)
- If you want an embedded database (H2, hsql or Derby), please put it on the classpath
- When using stm32g070 Hal library, if you want to write to flash, you must perform an erase. If you don't let it, you can't write continuously.
- Linux checks where the software is installed and what files are installed
- SQL statement fuzzy query and time interval filtering
- 69. Sqrt (x) (c + + problem solving version with vs runnable source program)
- Fresh students are about to graduate. Do you choose Java development or big data?
- Java project: OA management system (java + SSM + bootstrap + MySQL + JSP)
- Titanic passenger survival prediction
- Vectorization of deep learning formula
- Configuration and use of private image warehouse of microservice architect docker
- Relearn JavaScript events
- For someone, delete return 1 and return 0
- How does Java dynamically obtain what type of data is passed? It is used to judge whether the data is the same, dynamic data type
- How does the database cow optimize SQL?
- [data structure] chain structure of binary tree (pre order traversal) (middle order traversal) (post order traversal) (sequence traversal)
- Webpack packaging optimization solution
- 5. Operation element
- Detailed explanation of red and black trees
- redhat7. 9 install database 19C
- Blue Bridge Cup notes: (the given elements are not repeated) complete arrangement (arrangement cannot be repeated, arrangement can be repeated)
- Detailed explanation of springboot default package scanning mechanism and @ componentscan specified scanning path
- How to solve the run-time exception of test times
- Detailed explanation of k8s management tool kubectl
- Android system view memory command