Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Awesome features of RecyclerView

Awesome features of RecyclerView

RecyclerView widget was a big improvement over ListView in terms of flexibility. In this talk, I share some experience that I had when developing UIs with RecyclerView. Learn some tricks like animations, efficient data updates and more.

Tiago Almeida

November 23, 2017
Tweet

More Decks by Tiago Almeida

Other Decks in Programming

Transcript

  1. RecyclerView vs ListView • Display arbitrary number of items •

    Listview was designed for simple items • No animation support • Internal code is too complex • Changing ListView API could break existing apps
  2. ListView • It works fine for some cases • View

    recycling • ViewHolder pattern
  3. GridLayoutManager GridLayoutManager manager = new GridLayoutManager( this, 2, /*Number of

    columns*/ LinearLayoutManager.VERTICAL, false); manager.setSpanSizeLookup( new GridLayoutManager.SpanSizeLookup() { @Override public int getSpanSize(int position) { return position % 3 == 0 ? 2 : 1; } });
  4. Adapter • Create the View and ViewHolder • Bind data

    to the view • Support different view types
  5. ItemAnimator • Provides animations when data changes ◦ Add, Remove,

    Move, Change • Default implementation works great
  6. Use case 1 - Different layout managers <?xml version="1.0" encoding="utf-8"?>

    <android.support.v7.widget.RecyclerView android:id="@+id/recyclerView" android:layout_width= "match_parent" android:layout_height= "match_parent" />
  7. Use case 1 - Different layout managers boolean isTabletDevice =

    getResources().getBoolean(R.bool.isTabletDevice); if (isTabletDevice) { recyclerView.setLayoutManager(new GridLayoutManager(this, 3)); } else { recyclerView.setLayoutManager( new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)); } recyclerView.setAdapter(new MyAdapter(itemList));
  8. Implementing a shuffle action no animations :( private void shuffle(){

    Collections. shuffle(itemList); recyclerView.getAdapter().notifyDataSetChanged() ; }
  9. DiffUtil • No necessary ID • Calculates “Diff” of old

    and new collection • Applies changes to RecyclerView with animations
  10. DiffUtil Callback int getOldListSize () int getNewListSize () boolean areItemsTheSame

    (int oldItemPosition , int newItemPosition) boolean areContentsTheSame (int oldItemPosition , int newItemPosition)
  11. Adapter - Granular data updates Adapter::notifyItemChanged(int position, Object payload) void

    onBindViewHolder(RecyclerView.ViewHolder holder, int position, List payloads) { if (payloads.isEmpty()) { onBindViewHolder(holder, position); } else if (payloads.contains(LIKE)) { holder.itemView.likes.setText(item.likes); } }