gpt4 book ai didi

android - 是否可以通过Activity从 fragment 中调用ViewModel方法,或者这是一种不好的做法?

转载 作者:行者123 更新时间:2023-12-03 11:01:59 25 4
gpt4 key购买 nike

我有一个 Activity 和4个片段。首先,我想对ViewModel的每个片段进行操作。但是这种情况使得我也需要Activity的ViewModel。我想知道是否仅为Activity创建ViewModel并使用getActivity从片段中调用必要的方法是否会出错?例如,在片段处调用getActivity()。myViewModel.callMethod()?这种方法会错吗?

最佳答案

是的,您可以在一个片段上使用Activity的ViewModel,但不能像getActivity().myViewModel.callMethod()一样。应该是这样

YourViewModel viewModel = ViewModelProviders.of(getActivity()).get(YourViewModel.class);

在片段之间共享数据是一个好习惯。

Official doc of Google

That way, when the fragments each get the ViewModelProvider, they receive the same SharedViewModel instance, which is scoped to this activity.

This approach offers the following benefits:

  • The activity does not need to do anything, or know anything about this communication.
  • Fragments don't need to know about each other besides the SharedViewModel contract. If one of the fragments disappears, the other one keeps working as usual.
  • Each fragment has its own lifecycle, and is not affected by the lifecycle of the other one. If one fragment replaces the other one, the UI continues to work without any problems.

关于android - 是否可以通过Activity从 fragment 中调用ViewModel方法,或者这是一种不好的做法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57001254/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com