【问题标题】:Retrieve data from previous instance with navigation controller使用导航控制器从先前实例中检索数据
【发布时间】: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


    【解决方案1】:

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

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

    这将使 ViewModel 在您再次启动 Fragment 时保持“活动”,而不是在每次创建 Fragment 时都创建一个新的 AnnoncesViewModel。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多