是否可以使用返回字符串的ViewModel方法设置TextView的文本?

时间:2018-06-21 10:46:34

标签: android android-databinding android-mvvm

是否可以使用返回String的方法来更改TextView的文本?

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

编辑:当我设置android:text="@{viewmodel.userList.toString()}"时,它不返回绑定错误,但返回User对象的String表示形式。但是当我使用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>

1 个答案:

答案 0 :(得分:1)

您要使用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);
    }
}