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

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

我是android开发的新手,我使用“导航”库。
从我的第一个片段(这是一个从api获取数据的recyclerview)开始,如果我导航到另一个片段,导航控制器将销毁第一个片段并创建第二个片段并显示它。如果我想返回到第一个片段(使用左箭头或back按钮),它将销毁第二个片段并从头开始创建第一个片段,使其重新加载所有数据并使用bandwith。
我读过很多解决方案,但都很讲究:
使用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;
    }

viewmodel:

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);

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

aiqt4smr

aiqt4smr1#

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

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

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

相关问题