【问题标题】:How to manage Android MVVM, Android Architecture component (LiveData) with DataBinding for many UI fields?如何使用 DataBinding 为许多 UI 字段管理 Android MVVM、Android 架构组件(LiveData)?
【发布时间】:2019-03-28 10:58:48
【问题描述】:

我知道 Android MVVM、LiveData 和 DataBinding。但是,我有一个场景,其中我有许多输入 UI 字段,例如电子邮件、密码、确认密码等。我可以使用 ViewModel 映射这些字段。

public class LoginViewModel extends ViewModel {
        public MutableLiveData<String> email = new MutableLiveData<>();
        public MutableLiveData<String> password = new MutableLiveData<>();
        .
        .
        .
}

我用下面的 XML 布局绑定了这个 LoginViewModel。

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>

        <variable
            name="loginViewModel"
            type="viewModel.LoginViewModel" />

    </data>

    <RelativeLayout
        android:id="@+id/main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="10dp"
        tools:context=".view.MainActivity">


        <EditText
            android:id="@+id/editText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="textEmailAddress"
            android:text="@={loginViewModel.email}" />

        <EditText
            android:id="@+id/editText2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/editText"
            android:ems="10"
            android:inputType="textPassword"
            android:text="@={loginViewModel.password}" />

    </RelativeLayout>
</layout>

实际上,我有更多的 UI 字段,那么我应该遵循哪种理想的方法?是否根据我的 UI 在 ViewModel 中声明完全相同的 LiveData。就像 10 个 UI 字段在 ViewModel 中应该有 10 个 LiveData。

【问题讨论】:

  • 点击此链接这些对我有帮助medium.com/halcyon-mobile/…
  • @AravindV 感谢您的参考。实际上,我知道 LiveData 和数据绑定。您的链接没有传达我的问题的答案。

标签: android mvvm android-databinding android-livedata


【解决方案1】:

如果您的 UI 可以显示,您的视图模型应该公开 10 个数据字段(不要超载 UI)。这就是 MVVM 的工作原理。但!您应该根据字段行为公开不同类型的字段:

  • LiveData 用于只读字段(例如 TextView
  • MutableLiveData 用于可变字段,双向数据绑定(例如EditText
  • LiveData 类型用于常量(只读)数据。如果您知道数据在视图模型生命周期内未更改,则可以在不使用LiveData 的情况下公开数据。在这种情况下,当您设置视图模型变量时,您的数据将被绑定一次。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-01
    • 2018-10-21
    • 1970-01-01
    • 2018-02-28
    相关资源
    最近更新 更多