【发布时间】:2019-10-18 16:41:30
【问题描述】:
我最近开始学习 Android 架构组件(LiveData、ViewModel 和 Navigation)。所以我创建了一个底部导航应用程序。
我在这里放一些示例代码只是为了作为例子讨论。
SampleViewModel 类:-
public class DashboardViewModel extends ViewModel {
private MutableLiveData<String> mText;
public DashboardViewModel() {
mText = new MutableLiveData<>();
mText.setValue("This is dashboard fragment");
}
public LiveData<String> getText() {
return mText;
}
}
SampleFragmentClass:-
public class DashboardFragment extends Fragment {
private DashboardViewModel dashboardViewModel;
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
dashboardViewModel = ViewModelProviders.of(this).get(DashboardViewModel.class);
View root = inflater.inflate(R.layout.fragment_dashboard, container, false);
final TextView textView = root.findViewById(R.id.text_dashboard);
dashboardViewModel.getText().observe(this, new Observer<String>() {
@Override
public void onChanged(@Nullable String s) {
textView.setText(s);
}
});
return root;
}
}
让我明确一点,这些代码没有任何问题。
我只是想问一些问题:-
ViewModel是否完全负责加载将要加载的数据? 被活动或片段使用?如果我需要从服务器获取一些数据,我会调用 API 来自
ViewModel还是活动本身?如果我需要执行一些基于上下文的操作,我会在 活动或片段。是否有一些约定或指导方针,我 应该在 ViewModel 中做吗?
【问题讨论】:
标签: java android android-jetpack android-viewmodel