当前位置:网站首页>Jetpack -- navigation realizes page Jump
Jetpack -- navigation realizes page Jump
2022-07-29 02:13:00 【Y.IU.】
Navigation Components can make switching between pages easier .
Navigation It roughly includes four parts :
NavHost
NavHost Equivalent to a container , Used to store which pages can be accessed , Which pages can go out .
Fragment
Fragment The original purpose of the launch is to adapt to the large screen , Divide the large screen into small parts , Each small part is a Fragment.
NavController
NavController Logic used to control navigation , Press the key to switch to which page , The specific page to switch to depends on the navigation route .
NavGraph
NavGraph Shows the logical relationship between pages , That is, the switching relationship between pages , There are arrows between pages , Each arrow is a Action, from NavController To drive these Action, Then realize the switching of pages .
Code practice
First step : First create two Fragment.
fragment_home.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".fragment.HomeFragment" android:orientation="vertical" android:gravity="center" >
<TextView android:layout_width="100dp" android:layout_height="50dp" android:text=" Home page " android:gravity="center" />
<Button android:id="@+id/btn1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text=" Jump " />
</LinearLayout>
fragment_detail.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".fragment.HomeFragment" android:orientation="vertical" android:gravity="center" >
<TextView android:layout_width="100dp" android:layout_height="50dp" android:text=" Details page " android:gravity="center" />
<Button android:id="@+id/btn1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text=" Jump " />
</LinearLayout>
The second step : stay res Create under file Navigation Resource file , Used to design the roadmap (NavGraph).
have access to AS Provide visualization for design :
Click the green plus sign to add the page to be switched .
Each page is connected by arrows , Indicates that you can jump from a page to the page pointed by the arrow , Each arrow is a Action, Every Action There's a unique one id.
After that , We will find that Hosts The box will have the following prompt , Chinese meaning :“ The navigation map must start from NavHostFragment To access ”, This NavHostFragment Need to be in Activity Of xml Create in file , See Step 3 for details .
This is the code part
<?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/nav_graph" app:startDestination="@id/homeFragment">
<fragment android:id="@+id/homeFragment" android:name="com.example.navigationtest.fragment.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.navigationtest.fragment.DetailFragment" android:label="DetailFragment" >
<action android:id="@+id/action_detailFragment_to_homeFragment2" app:destination="@id/homeFragment" />
</fragment>
</navigation>
The third step : establish NavHostFragment
stay activity_main.xml Choose from NavHostFragment Drag to the layout on the right .

Then there will be the following prompt , Select the navigation map you want to access , Click on “OK” that will do .

Returning to the navigation map file, we can see NavHostFragment It's connected .
The code is as follows :
<?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">
<androidx.fragment.app.FragmentContainerView android:id="@+id/fragmentContainerView2" android:name="androidx.navigation.fragment.NavHostFragment" android:layout_width="409dp" android:layout_height="729dp" app:defaultNavHost="true" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:navGraph="@navigation/nav_graph" tools:layout_editor_absoluteY="1dp" tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>
Step four : Use NavControler To control the logic of navigation .
First , The jump of the page must be triggered by the user clicking on a control or key , So when dealing with click events, realize page Jump . The core code is as follows :
NavController controller = Navigation.findNavController(v); // Get controller
controller.navigate(R.id.action_homeFragment_to_detailFragment); // call navigation Method to realize page Jump , This method needs to pass a Action Of id, Indicates that you want to execute this jump behavior .
HomeFragment
public class HomeFragment extends Fragment {
public HomeFragment() {
// Required empty public constructor
}
@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) {
Button button = (Button) view.findViewById(R.id.btn1);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
NavController controller = Navigation.findNavController(v);
controller.navigate(R.id.action_homeFragment_to_detailFragment);
}
});
}
}
Use NavController The second way to write control navigation logic , This kind of writing is more concise .
button.setOnClickListener(Navigation.createNavigateOnClickListener(R.id.action_detailFragment_to_homeFragment2));
DetailFragment
public class DetailFragment extends Fragment {
public DetailFragment() {
// Required empty public constructor
}
@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) {
Button button = (Button) view.findViewById(R.id.btn1);
button.setOnClickListener(Navigation.createNavigateOnClickListener(R.id.action_detailFragment_to_homeFragment2));
}
}
thus , The basic jump function has been realized , But if you want to click the fallback button in the upper left corner to realize the fallback function, how to realize it ? Of course ,Navigation It also provides us with this function , As follows :
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
NavHostFragment fragment = (NavHostFragment)getSupportFragmentManager().findFragmentById(R.id.fragmentContainerView);
NavController controller = fragment.getNavController();
NavigationUI.setupActionBarWithNavController(this,controller);
}
@Override
public boolean onSupportNavigateUp() {
NavController controller = Navigation.findNavController(this,R.id.fragmentContainerView);
return controller.navigateUp();
}
}
边栏推荐
- As long as I run fast enough, it won't catch me. How does a high school student achieve a 70% salary increase under the epidemic?
- How to find the right agent type? Multi angle analysis for you!
- MotionLayout--在可视化编辑器中实现动画
- MySQL stores JSON format data
- Resolve the conflict with vetur when using eslint, resulting in double quotation marks and comma at the end of saving
- Why can't Bi software do correlation analysis
- Mathematical modeling -- cold proof simulation of low temperature protective clothing with phase change materials
- Probability Density Reweight
- How to crawl web pages with playwright?
- druid. io index_ Realtime real-time query
猜你喜欢

(arxiv-2018) 重新审视基于视频的 Person ReID 的时间建模

druid. io kill -9 index_ Realtime traceability task

Control buzzer based on C51

E-commerce keyword research helps data collection

Large scale web crawling of e-commerce websites (Ultimate Guide)

Mathematical modeling -- bus scheduling optimization

Implementation of 10m multifunctional signal generator with FPGA

JS dom2 and dom3

Cookie和Session

Blind separation of speech signals based on ICA and DL
随机推荐
Opencv image sharpness evaluation (camera autofocus)
「活动推荐」冲冲冲!2022 国际开源节有新内容
Solution of Lenovo notebook camera unable to open
E-commerce keyword research helps data collection
In 2022, the official data of programming language ranking came, which was an eye opener
Jetpack--了解ViewModel和LiveData的使用
Control the pop-up window and no pop-up window of the input box
2022.7.28-----leetcode.1331
MySQL stores JSON format data
druid. IO custom real-time task scheduling policy
mobile-picker.js
(arxiv-2018) 重新审视基于视频的 Person ReID 的时间建模
2022年编程语言排名,官方数据来了,让人大开眼界
使用本地缓存+全局缓存实现小型系统用户权限管理
The growth path of embedded engineers
Type analysis of demultiplexer (demultiplexer)
[circuit design] convert AC AC to DC
Click the button to slide to the specified position
第十四天:续第十三天标签相关知识
2022.7.28-----leetcode.1331