使用导航控制器从以前的示例检索数据

pdkcd3nj  于 2021-07-04  发布在  Java
关注(0)|答案(1)|浏览(288)

我是android开发的新手,我使用“导航”库。
从我的第一个片段(这是一个从api获取数据的recyclerview)开始,如果我导航到另一个片段,导航控制器将销毁第一个片段并创建第二个片段并显示它。如果我想返回到第一个片段(使用左箭头或back按钮),它将销毁第二个片段并从头开始创建第一个片段,使其重新加载所有数据并使用bandwith。
我读过很多解决方案,但都很讲究:
使用mvvm
编写自己的导航控制器
使用mvp
我想知道在不调用api的情况下检索数据的更好方法是什么。
我的第一个片段:

  1. public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
  2. AnnoncesViewModel annoncesViewModel = new ViewModelProvider(this).get(AnnoncesViewModel.class);
  3. root = inflater.inflate(R.layout.fragment_annonces, container, false);
  4. ctx = root.getContext();
  5. recyclerView = root.findViewById(R.id.listeannonce_rv);
  6. annoncesViewModel.getAnnonces().observe(this, data-> {
  7. recyclerViewAdapter = new ListeAnnoncesAdapter(data, ctx, AnnoncesFragment.this);
  8. recyclerView.setLayoutManager(new LinearLayoutManager(root.getContext()));
  9. recyclerView.setAdapter(recyclerViewAdapter);
  10. });
  11. return root;
  12. }

viewmodel:

  1. public class AnnoncesViewModel extends ViewModel {
  2. MutableLiveData<ArrayList<Annonce>> annonces;
  3. ArrayList<Annonce> AnnonceArrayList;
  4. public AnnoncesViewModel() {
  5. annonces = new MutableLiveData<>();
  6. AnnonceArrayList = new ArrayList<>();
  7. annonces.setValue(AnnonceArrayList);
  8. }
  9. public MutableLiveData<ArrayList<Annonce>> getAnnonces() {
  10. return annonces;
  11. }
  12. }

对于导航,我使用

  1. navController.navigate(R.id.frag1_to_frag2);

  1. navController.navigate(R.id.nav_frag2);

但这并没有改变什么。
目前,当我按下一个按钮时,数据就会被检索出来。
谢谢你的帮助!

aiqt4smr

aiqt4smr1#

viewmodel方法是正确的选择。问题是,当您导航到新片段时,annoncesviewmodel也会被破坏,因为您正在将片段上下文传递给viewmodelprovider。要在导航到其他片段后保留viewmodel,请将活动上下文传递给提供程序,如:

  1. ViewModelProviders.of(requireActivity()).get(AnnoncesViewModel::class.java)

当您再次启动片段时,这将使viewmodel保持“活动”状态,而不是每次创建片段时都创建一个新的annoncesviewmodel。

相关问题