【发布时间】:2020-09-06 16:10:32
【问题描述】:
我对 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);
但它不会改变任何东西。
此刻,当我按下按钮时,数据被检索。
感谢您的帮助!
【问题讨论】:
标签: java android android-recyclerview viewmodel