【问题标题】:Databinding with ViewModel and Model使用 ViewModel 和 Model 进行数据绑定
【发布时间】:2019-06-01 12:55:30
【问题描述】:

(这里是法语,对可能的误解深表歉意)

我是 Android 数据绑定的新手,我正在努力解决一个相当简单的问题。

假设我有这个 POJO,我们将把它视为我的模型的一部分

public class User
{
    public String name;

    public User(String name)
    {
        this.name = name;
    }
}

现在我有一个包含用户的 ViewModel

public class MyViewModel extends ViewModel
{
    private User user = new User("blue");

    public String getName()
    {
        return user.name;
    }

    public void setName(String name)
    {
        user.name = name;
    }
}

我希望视图(活动)能够在此“名称”字段上进行双向数据绑定。我知道如何做 Activity 和 XML 的东西,比如设置 Binding 类等。我不知道的是,如何使 ViewModel 可观察到 User 类的“name”字段的任何更改。请注意,我不想通过以下方式使我的 User 类可观察:

public class User
{
    public MutableLiveData<String> name;

    public User(String name)
    {
        this.name.setValue(name);
    }
}

因为我个人更喜欢让这些 Android 东西远离我的模型。

如何更改我的 ViewModel 以便 View 可以收听“名称”的更改?我已经看到了一些带有 @Bindable 注释的东西,但我不太确定如何使用它。

感谢您的帮助

【问题讨论】:

    标签: android data-binding androidx android-jetpack two-way


    【解决方案1】:

    在你的布局文件中,你会有类似的东西:

    <data>
        <variable name="vm" type="<your_package>.MyViewModel" />
    </data>
    

    然后你可能有类似TextView 的东西,它使用以下方式绑定到名称:

            <TextView
                android:id="@+id/name"
                android:text="@{vm.name}"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>
    

    您需要做的另一件重要事情是在您的活动/片段中调用以下内容:

    binding.setLifecycleOwner(this)
    

    (连同binding.vm = yourViewModelInstance

    【讨论】:

    • 所以我不必在 ViewModel 中使用任何 LiveData 或 ObservableFields 吗?我现在正在更新Android Studio,我看看它是否有效,但它让我感到惊讶哈哈
    • 啊,我错过了你没有在ViewModel 中使用LiveData...是的,以上将基于使用它
    • @CharlyLafon 是否有理由在您的 ViewModel 中不能有 MutableLiveData&lt;User&gt; 之类的东西?
    • 没有用 Android 绑定的东西填充 ViewModel 很酷。我不想触及 User 类,仅此而已。因此,您认为将用户字段设为 MutableLiveData 是解决方案(抱歉,我仍然无法尝试您的答案,我的 android studio 正在努力更新)?我认为它不起作用,因为我想听用户的“名称”字段的变化,而不是用户本身的变化。
    • 如果只想管理名称字符串,您也可以在ViewModel 中使用MutableLiveData&lt;String&gt;,但我认为将它用于User 可能更灵活。在您的布局中,您应该能够绑定到 vm.user.name 之类的东西
    【解决方案2】:
    You can add Bindable like this in your POJO Class
    
    public class User extends BaseObservable
    {
      public String name;
      public User(String name)
      {
        this.name = name;
      }
    
     @Bindable
     public String getName() 
     {
        return name;
     }
    
     public void setName(String name)
     {
        this.name = name;
        notifyPropertyChanged(BR.name);
    }
    }
    

    【讨论】:

    • 我可以在不接触 POJO 类的情况下做这样的事情吗?只有 ViewModel。
    猜你喜欢
    • 2011-01-21
    • 2013-06-14
    • 1970-01-01
    • 2012-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-05
    • 2020-09-21
    相关资源
    最近更新 更多