I am using the ListAdapter in the Support library along with LiveData to observe my Room database (my implementation is similar to the one shown here). For some reason, my recycler view is not animating when the data is updated. The new items get added to the adapter however they remain outside the recycler view so I have to manually scroll up to view them. Why is this happening?
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));
}
}
In my fragment -
@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);
}
});
}