首页 > 解决方案 > 是否可以使用返回字符串的 ViewModel 方法设置 TextView 的文本?

问题描述

是否可以使用返回字符串的方法更改 TextView 的文本?

出于培训目的,我创建了这个ViewModel类,它将User对象放入List<User> mUserList其中,我想知道我是否可以使用 ViewMode 方法将此用户的名字设置为 TextView 的文本。我收到绑定错误,是否可以使用不使用 @BindingAdapter 注释返回 String 的方法来解决此问题?

编辑:当我设置android:text="@{viewmodel.userList.toString()}"它不返回绑定错误但它返回用户对象的字符串表示。但是当我使用android:text="@{viewmodel.getUserFirstNames()}"我得到一个绑定错误。为什么会这样?

public class UsersViewModel extends ViewModel {

    private List<User> mUserList;

    public List<User> getUserList() {
        if (mUserList == null) {
            mUserList = loadUsers();
        }
        return mUserList;
    }

    /**
     * Dummy Method to fake web service
     *
     * @return list of users
     */
    private List<User> loadUsers() {
    // do something to load users
    List<User> userList = new ArrayList<>();
    User user = new User();
    user.setFirstName("John");
    user.setLastName("Adams");
    userList.add(user);

    user = new User();
    user.setFirstName("Lucy");
    user.setLastName("Adams");
    userList.add(user);

    return userList;

    }


    @NonNull
    private String getUserFirstNames() {
        if (mUserList != null && mUserList.size() > 0) {
            StringBuilder sb = new StringBuilder();
            sb.append("First Names:\n");
            for (User user : mUserList) {
                sb.append(user.getFirstName() + "\n");
            }

            return sb.toString();
        }

        return "empty";
    }
}

在 MainActivity 我假装使用公共类 MainActivity 加载数据扩展 AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ActivityMainBinding activityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);

        UsersViewModel usersViewModel =
                ViewModelProviders.of(this).get(UsersViewModel.class);
        usersViewModel.getUserList();
        activityMainBinding.setViewmodel(usersViewModel);
    }
}

在布局中我想知道是否可以使用 ViewModel 类设置 TextView 的文本

    <data>

        <variable
            name="viewmodel"
            type="com.example.tutorial1basics.viewmodel.UsersViewModel" />
    </data>

    <android.support.constraint.ConstraintLayout 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"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">

        <TextView
            android:id="@+id/tv_users"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{viewmodel.getUserFirstNames()}"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />



    </android.support.constraint.ConstraintLayout>
</layout>

标签: androidandroid-databindingandroid-mvvm

解决方案


您想使用 BaseObservable 扩展您的模型。

喜欢 :

public class Post extends BaseObservable{
    @SerializedName("userId")
    @Expose
    private Integer userId;
    @SerializedName("id")
    @Expose
    private Integer id;
    @SerializedName("title")
    @Expose
    private String title;
    @SerializedName("body")
    @Expose
    private String body;

    @Bindable
    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
        notifyPropertyChanged(BR.userId);
    }

    @Bindable
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
        notifyPropertyChanged(BR.id);
    }

    @Bindable
    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
        notifyPropertyChanged(BR.title);
    }

    @Bindable
    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
        notifyPropertyChanged(BR.body);
    }
}

推荐阅读