使用DiffUtil ListAdapter时,Recyclerview不会设置动画

时间:2018-04-11 08:40:44

标签: android android-recyclerview

我使用支持库中的ListAdapter和LiveData来观察我的房间数据库(我的实现类似于here所示的实现)。出于某种原因,我的Recycler视图在更新数据时不会动画。新项目将添加到适配器,但它们仍然在回收站视图之外,因此我必须手动向上滚动才能查看它们。为什么会这样?

ItemAdapter.java

public class ItemRecyclerAdapter extends ListAdapter<Item, PostViewHolder> {
    public static final DiffUtil.ItemCallback<Item> DIFF_CALLBACK =
            new DiffUtil.ItemCallback<Item>() {
                @Override
                public boolean areItemsTheSame(
                        @NonNull Item oldItem, @NonNull Item newItem) {
                    return Objects.equals(oldItem.id, newItem.id);
                }

                @Override
                public boolean areContentsTheSame(
                        @NonNull Item oldItem, @NonNull Item newItem) {
                    return Objects.equals(oldItem.content, newItem.content);
                }
            };

    public ItemRecyclerAdapter() {
        super(DIFF_CALLBACK);
    }

    @NonNull
    @Override
    public PostViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new PostViewHolder(LayoutInflater.from(parent.getContext())
                .inflate(R.layout.post_item, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull PostViewHolder holder, int position) {
        holder.onBind(getItem(position));
    }
}

在我的片段中 -

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
        adapter = new ItemRecyclerAdapter();
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));

        viewModel = ViewModelProviders.of...
        viewModel.setData(...);
        viewModel.getPosts().observe(this, listResource -> {
        if (listResource != null && listResource.data != null) {
            adapter.submitList(listResource.data);
        }
    });
}

1 个答案:

答案 0 :(得分:1)

喜欢使用下面的代码 用户pojo类

    @Entity
public class User {
    public static DiffCallback<User> DIFF_CALLBACK = new DiffCallback<User>() {
        @Override
        public boolean areItemsTheSame(@NonNull User oldItem, @NonNull User newItem) {
            return oldItem.userId == newItem.userId;
        }

        @Override
        public boolean areContentsTheSame(@NonNull User oldItem, @NonNull User newItem) {
            return oldItem.equals(newItem);
        }
    };

    @SerializedName("id")
    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "user_id")
    public long userId;

    @SerializedName("login")
    @ColumnInfo(name = "first_name")
    public String firstName;
    public String address;

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

        User user = (User) obj;

        return user.userId == this.userId && user.firstName == this.firstName;
    }
}

然后在适配器之后代码..

public class UserAdapter extends ListAdapter<User, UserAdapter.UserItemViewHolder> {


public UserAdapter() {
    super(User.DIFF_CALLBACK);
}

@Override
public UserItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
    View view = layoutInflater.inflate(R.layout.item_user_list, parent, false);
    return new UserItemViewHolder(view);
}

@Override
public void onBindViewHolder(UserItemViewHolder holder, int position) {
    User user= getItem(position);
    if(user!=null) {
        holder.bindTo(user);
    }
}

static class UserItemViewHolder extends RecyclerView.ViewHolder {
    TextView userName, userId;

    public UserItemViewHolder(View itemView) {
        super(itemView);
        userId = itemView.findViewById(R.id.userId);
        userName = itemView.findViewById(R.id.userName);
    }

    public void bindTo(User user) {
        userName.setText(user.firstName);
        userId.setText(String.valueOf(user.userId));
    }
}

}

并查看下面的模型类..

public class UserViewModel extends ViewModel {

public LiveData<PagedList<User>> userList;

public UserViewModel() {

}

public void init(UserDao userDao) {
   PagedList.Config pagedListConfig =
            (new PagedList.Config.Builder()).setEnablePlaceholders(true)
                    .setPrefetchDistance(10)
                    .setPageSize(20).build();

    userList = (new LivePagedListBuilder(userDao.usersByFirstName(), pagedListConfig))
            .build();
}

}

recycleler view绑定数据,如下面的代码..

    private void initView() {
    RecyclerView recyclerView = findViewById(R.id.plRvData);
    LinearLayoutManager llm = new LinearLayoutManager(this);
    llm.setOrientation(LinearLayoutManager.VERTICAL);
    recyclerView.setLayoutManager(llm);
    userDao=demoDatabase.getUserDao();
    UserViewModel viewModel = ViewModelProviders.of(this).get(UserViewModel.class);
    viewModel.init(userDao);
    final UserAdapter userUserAdapter = new UserAdapter();

    viewModel.userList.observe(this, pagedList -> {
        userUserAdapter.setList(pagedList);
    });
    Log.d("Vikas:::","Vikas PAndey");
    recyclerView.setAdapter(userUserAdapter);

}