观察RecyclerView(架构组件)的每个元素

时间:2017-10-25 10:07:29

标签: android android-recyclerview android-databinding android-architecture-components

我试图弄清楚创建元素列表的最佳方法是什么(每个元素使用数据绑定来设置数据)并观察每个元素的变化。实际上我有一个带有MutableLiveData列表MutableLiveData<List<ElementModel>>的ViewModel。

问题在于,每个元素都有上传文件或输入密码等操作,因此我必须在操作完成或加载时更改UI。我在RecyclerView适配器中尝试使用notifyItemChanged,但动画非常糟糕,使用executePendingBindings更新布局时效果更好

有没有女巫是解决这个问题的最好方法?

1 个答案:

答案 0 :(得分:-1)

如果使用equals,则对象必须正确覆盖Object#equals()。 在此处错误地返回false将导致动画过多。

 public static final DiffCallback<User> DIFF_CALLBACK = new DiffCallback<User>() {
            @Override
            public boolean areItemsTheSame(@NonNull User oldUser, @NonNull User newUser) {
                // User properties may have changed if reloaded from the DB, but ID is fixed
                return oldUser.getId() == newUser.getId();
            }
            @Override
            public boolean areContentsTheSame(@NonNull User oldUser, @NonNull User newUser) {
                // NOTE: if you use equals, your object must properly override Object#equals()
                // Incorrectly returning false here will result in too many animations.
                return oldUser.equals(newUser);
            }

用户类如下

public class UserInfo{
    @PrimaryKey
    @NonNull
    private String number;

    private String name;

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

    public String getName() {
        return name;
    }

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

    public UserInfo(String number, String name) {
        this.number = number;
        this.name = name;
    }



    @Override
    public boolean equals(Object obj) {
        if (obj == this)
            return true;

        UserInfo user = (UserInfo) obj;

        return user.number == this.number && user.name == this.name;
    }


    public static DiffCallback<UserInfo> DIFF_CALLBACK = new DiffCallback<UserInfo>() {
        @Override
        public boolean areItemsTheSame(@NonNull UserInfo oldItem, @NonNull UserInfo newItem) {
            return oldItem.number.equals(newItem.number);
        }

        @Override
        public boolean areContentsTheSame(@NonNull UserInfo oldItem, @NonNull UserInfo newItem) {
            // If this comparisons  wrong then to many UI changes in RecycleView
            return oldItem.equals(newItem);
        }

        @Override
        public Object getChangePayload(@NonNull UserInfo oldItem, @NonNull UserInfo newItem) {
            return super.getChangePayload(oldItem, newItem);
        }
    };
}

请参阅link