使用导航控制器从上一个实例检索数据



我对Android开发有点陌生,我使用"导航"库。

从我的第一个片段开始(这是一个从API获取数据的回收视图(,如果我导航到另一个片段,导航控制器会销毁第一个片段并创建第二个片段并显示它。如果我想返回第一个片段(用左箭头或后退按钮(,它会销毁第二个碎片并从头开始创建第一个片段,使其重新加载所有数据并使用带宽。

我读过很多解决方案,但都很挑剔:

  • 使用mvvm
  • 编写自己的导航控制器
  • 使用mvp

我想知道在不重新调用API的情况下检索数据的更好方法是什么。

我的第一个片段:

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

视图模型:

public class AnnoncesViewModel extends ViewModel {
MutableLiveData<ArrayList<Annonce>> annonces;
ArrayList<Annonce> AnnonceArrayList;
public AnnoncesViewModel() {
annonces = new MutableLiveData<>();
AnnonceArrayList = new ArrayList<>();
annonces.setValue(AnnonceArrayList);
}
public MutableLiveData<ArrayList<Annonce>> getAnnonces() {
return annonces;
}
}

对于导航,我使用

navController.navigate(R.id.frag1_to_frag2);

navController.navigate(R.id.nav_frag2);

但这并没有改变任何事情。

目前,当我按下一个按钮时,数据就会被检索出来。

谢谢你的帮助!

ViewModel方法是正确的选择。问题是,当您导航到新片段时,AnnancesViewModel也会被销毁,因为您正在将片段上下文传递给ViewModelProvider。要在导航到其他片段后保留ViewModel,请将活动上下文传递给提供者,如:

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

这将保持ViewModel";"活着";当您再次启动Fragment时,而不是每次创建Fragment都创建一个新的AnnancesViewModel。

最新更新