【问题标题】:MVVM & Binding & ContextMVVM & 绑定 & 上下文
【发布时间】:2021-12-31 15:50:13
【问题描述】:

我的同事和我发生了争执。 我们正在将应用程序转换为 MVVM+Binding。 需要从片段开始对话。 我是这样做的:

在片段中:

fragmentBinding.button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
     AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
       // there's a bunch of code here 
     alertDialog.show();
}});

一位同事还声称您需要这样做:

在xml文件中我们这样写:

android:onClick="@{v -> viewModel.showDialog(context)}"

在 ViewModel 中:

fun showDialog(context: Context){
     AlertDialog.Builder builder = new AlertDialog.Builder(context);
       // there's a bunch of code here
     alertDialog.show();
}

请告诉我,哪个是正确的?

【问题讨论】:

    标签: android mvvm binding


    【解决方案1】:

    ViewModel 负责为 UI 准备数据,如 Android Developer Guides 中所述。

    因此,一种最佳做法是永远不要在 ViewModel 中处理 UI 元素。尽管如果我们将Context 传递给 ViewModel 并允许它显示alertDialog,代码仍然会执行,但您可能还需要注意活动/片段和 ViewModel 具有不同的生命周期,因此您需要将Context 传递给 ViewModel 时要小心

    处理这个问题的更明智的方法是让 ViewModel 维护一个标志并使用 LiveData 或类似的东西准备所需的消息,以便活动/片段观察到并实际构建并显示 AlertDialog通过从 ViewModel 获取消息,并在对话框显示/单击时通知 ViewModel,以便 ViewModel 处理后续业务逻辑。

    对于您的特定情况,我会将AlertDialog 代码保留在活动/片段中,而如有必要,我将从 ViewModel 中检索数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-14
      • 2020-02-11
      • 1970-01-01
      • 2020-05-08
      • 2011-04-19
      • 1970-01-01
      • 2013-01-23
      • 2023-04-03
      相关资源
      最近更新 更多