当前位置:网站首页>Navigation -- realize data transmission and data sharing between fragments
Navigation -- realize data transmission and data sharing between fragments
2022-07-29 02:13:00 【Y.IU.】
Navigation chart Arugments Static transfer
In the built multi visual navigation map , Select the one that needs to accept data Fragment, For example, select here detailFragment.
And then in Attributes Hurdles Arguments Click “+” Button to add key value pairs , Fill in the name of the data to be transferred 、 type 、 Value and so on .
And then in DetailFragment.java Write code in the file to accept data , As follows :
adopt **getArguments().getString(“name”)** get data ,getArugments The specific method to call depends on the data type .
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) {
super.onViewCreated(view, savedInstanceState);
TextView tv = view.findViewById(R.id.tv1);
String text = getArguments().getString("name"); // adopt getArguments().getString("name") get data
tv.setText(text);
}
}
Bundle
Use Argument The method of adding key value pairs to transmit data can only achieve static transmission , If the data is dynamic , Then this method is difficult to achieve . adopt Bundle Method to realize data transmission is also very simple , Just create Bundle object , Then add key value pairs , When you switch pages, you will Bundle Just pass the object , The method of getting data from the page receiving data remains unchanged .
HomeFragment.java
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) {
super.onViewCreated(view, savedInstanceState);
Button button = view.findViewById(R.id.btn1);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Bundle bundle = new Bundle();
bundle.putString("name"," Xiaohong ");
NavController controller = Navigation.findNavController(v);
controller.navigate(R.id.action_homeFragment_to_detailFragment,bundle);
}
});
}
}
adopt ViewModel+LiveData+Databinding Realization Fragment Data sharing and transmission between
Create two Fragment, Write the layout , Realize data binding in layout , Build the navigation map , The final effect is shown in the figure below , How to implement it will not be introduced in detail , Because this is mainly about how to realize data sharing . You can see in the jump process of the page , The numbers have not changed .
Customize ViewModel class :
public class MyViewModel extends ViewModel {
private MutableLiveData<Integer> liveData;
public MutableLiveData<Integer> getCurrent() {
if(liveData == null) {
liveData = new MutableLiveData<Integer>();
liveData.setValue(0); // You have to set , Otherwise, null pointer exceptions may occur when obtaining .
}
return liveData;
}
public void add(int num) {
liveData.setValue(liveData.getValue() + num);
}
}
stay HomeFragment Class onCreateView In the method , Perform data binding , Different from the previous data binding , It used to be setContentView To set the layout file , And here is using inflate To set the layout file .
For one Activity Two or more of Fragment, Because of these Fragment Subordinate Activity Is the same , In these Fragment Use in getActivity() Method gets the same Activity, So pass ViewModelProvider Acquired ViewModel It's the same object , This is also the meaning of singleton mode , So we can achieve Fragment Data sharing between .
HomeFragment.java
public class HomeFragment extends Fragment implements View.OnClickListener {
private MyViewModel viewModel;
public HomeFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
// Data binding
FragmentHomeBinding binding = DataBindingUtil.inflate(inflater,R.layout.fragment_home,container,false);
viewModel = new ViewModelProvider(getActivity()).get(MyViewModel.class);
binding.setData(viewModel);
binding.setLifecycleOwner(getActivity());
return binding.getRoot();
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Button button = view.findViewById(R.id.btn1);
Button addBtn = view.findViewById(R.id.addBtn);
Button subBtn = view.findViewById(R.id.subBtn);
button.setOnClickListener(this);
addBtn.setOnClickListener(this);
subBtn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn1:
NavController controller = Navigation.findNavController(v);
controller.navigate(R.id.action_homeFragment_to_detailFragment2);
break;
case R.id.addBtn:
viewModel.add(1);
break;
case R.id.subBtn:
viewModel.add(-1);
break;
}
}
}
stay DetailFragment Class is similar .
DetailFragment.java
public class DetailFragment extends Fragment implements View.OnClickListener{
private MyViewModel viewModel;
public DetailFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
FragmentDetailBinding binding = DataBindingUtil.inflate(inflater,R.layout.fragment_detail,container,false);
viewModel = new ViewModelProvider(getActivity()).get(MyViewModel.class);
binding.setData(viewModel);
binding.setLifecycleOwner(getActivity());
return binding.getRoot();
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Button button = view.findViewById(R.id.btn1);
Button addBtn = view.findViewById(R.id.addBtn);
Button subBtn = view.findViewById(R.id.subBtn);
button.setOnClickListener(this);
addBtn.setOnClickListener(this);
subBtn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
MyViewModel viewModel = new ViewModelProvider(getActivity()).get(MyViewModel.class);
switch (v.getId()) {
case R.id.btn1:
NavController controller = Navigation.findNavController(v);
controller.navigate(R.id.action_detailFragment_to_homeFragment);
break;
case R.id.addBtn:
viewModel.add(1);
break;
case R.id.subBtn:
viewModel.add(-1);
break;
}
}
}
Project address :https://gitee.com/yxl-17/jet-pack_-navigation
边栏推荐
- 点击回到顶部js
- 表单校验 隐藏的输入框 显示才校验
- Dynamic memory and smart pointer
- 试着换个角度理解低代码平台设计的本质
- Basic working principle and LTSpice simulation of 6T SRAM
- H5 background music is played automatically by touch
- 12. < tag dynamic programming and subsequence, subarray> lt.72. edit distance
- 全志T3/A40i工业核心板,4核[email protected],国产化率达100%
- Jetpack--了解ViewModel和LiveData的使用
- The basic concept of transaction and the implementation principle of MySQL transaction
猜你喜欢

Introduction to shared data center agent

基于C51实现数码管的显示

druid. io kill -9 index_ Realtime traceability task

druid. The performance of IO + tranquility real-time tasks is summarized with the help of 2020 double 11

Control buzzer based on C51

Comprehensive explanation of "search engine crawl"

Type analysis of demultiplexer (demultiplexer)
![What is a proxy server? [2022 guide]](/img/d8/f9ff56608ab42df9127493bc038961.png)
What is a proxy server? [2022 guide]

Motionlayout -- realize animation in visual editor

Mathematical modeling -- red wine quality classification
随机推荐
MySQL之数据查询(多表查询)
(CVPR-2019)选择性的内核网络
Why can't Bi software do correlation analysis
点击按钮,下滑到指定的位置
试着换个角度理解低代码平台设计的本质
2022.7.28-----leetcode.1331
Dynamic memory and smart pointer
Related function records about string processing (long-term update)
MySQL high performance optimization notes (including 578 pages of notes PDF document), collected
leetcode/0和1个数相同的连续子数组
The number of consecutive subarrays whose leetcode/ product is less than k
Mathematical modeling - location of police stations
Navigation--实现Fragment之间数据传递和数据共享
Leetcode exercise - Sword finger offer 45. arrange the array into the smallest number
费曼学习法(符号表)
Introduction to shared data center agent
数学建模——带相变材料的低温防护服御寒仿真模拟
【云原生与5G】微服务加持5G核心网
Idea connection database
LM13丨形态量化-动量周期分析