SimpleRecyclerView

Additional

Language
Java
Version
N/A
Created
Feb 3, 2017
Updated
Dec 10, 2018
Owner
Jay (jaychang0917)
Contributors
Jay (jaychang0917)
jaychang0917redso
Deividas Strioga (deividasstr)
3
Activity
Badge
Generate
Download
Source code
APK file

Show card

SimpleRecyclerView

A RecyclerView extension for building list more easily.

Screenshot

Table of Contents

Sample Project

Installation

In your app level build.gradle :

dependencies {
    implementation 'com.jaychang:simplerecyclerview:2.0.5'
    // for kotlin android extensions
    implementation 'com.jaychang:simplerecyclerview-kotlin-android-extensions:2.0.5'
}

Basic Usage

Basically, there are three steps to build your list.

1. Configure the SimpleRecyclerView

Full attributes list

<com.jaychang.srv.SimpleRecyclerView
    android:id="@+id/recyclerView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:srv_layoutMode="linearVertical|linearHorizontal|grid" 
    app:srv_gridSpanCount="integer"
    app:srv_gridSpanSequence="integer string (e.g. 2233)"
    ... />

2. Define the cell by extending SimpleCell<T, VH>

/**
 * Accept two type arguments,
 * 1st is the data model this cell represents, 2nd is the view holder.
 * */
public class BookCell extends SimpleCell<Book, BookCell.ViewHolder> {

  /** 
   * Mandatory constructor, pass your data model as argument 
   * */
  public BookCell(Book item) {
    super(item);
  }

  /**
   * Define the layout resource of this cell
   * */
  @Override
  protected int getLayoutRes() {
    return R.layout.cell_book;
  }

  @NonNull
  @Override
  protected ViewHolder onCreateViewHolder(ViewGroup parent, View cellView) {
    return new ViewHolder(cellView);
  }

  @Override
  protected void onBindViewHolder(ViewHolder holder, int position, Context context, Object payload) {
    holder.textView.setText(getItem().getTitle());
  }
  
  /**
   * Optional
   * */
  @Override
  protected void onUnbindViewHolder(ViewHolder holder) {
    // do your cleaning jobs here when the item view is recycled.
  }

  /**
   * Define your view holder, which must extend SimpleViewHolder.
   * */
  static class ViewHolder extends SimpleViewHolder {
    TextView textView;

    ViewHolder(View itemView) {
      super(itemView);
      textView = itemView.findViewById(R.id.textView);
    }
  }

}
Kotlin android extensions support

If you are using Kotlin android extensions, the cell can be simplified as following:

class BookCell(item: Book) : SimpleCell<Book>(item) {
  override fun getLayoutRes(): Int {
    return R.layout.cell_book
  }

  override fun onBindViewHolder(holder: SimpleViewHolder, position: Int, context: Context, payload: Any) {
    holder.textView.text = item.title
  }
}

3. Create cell(s) and add them to the SimpleRecyclerView

List<Book> books = DataUtils.getBooks();
List<BookCell> cells = new ArrayList<>();

for (Book book : books) {
  BookCell cell = new BookCell(book);
  // There are two default cell listeners: OnCellClickListener<T> and OnCellLongClickListener<T>
  cell.setOnCellClickListener(new SimpleCell.OnCellClickListener<Book>() {
    @Override
    public void onCellClicked(Book item) {
      ...
    }
  });
  cell.setOnCellLongClickListener(new SimpleCell.OnCellLongClickListener<Book>() {
    @Override
    public void onCellLongClicked(Book item) {
      ...
    }
  });
  cells.add(cell);
}

simpleRecyclerView.addCells(cells);

Then, there you go!

Multiple Types

SimpleRecyclerView supports multiple cell types. You can add different type of cells to it just like adding different type of objects to a list. The SimpleRecyclerView will handle the rest for you.

List<Book> books = DataUtils.getBooks();
List<Ad> ads = DataUtils.getAds();
List<SimpleCell> cells = new ArrayList<>();

for (Book book : books) {
  BookCell cell = new BookCell(book);
  cells.add(cell);
}

for (Ad ad : ads) {
  BookAdCell cell = new BookAdCell(ad);
  int position = (ads.indexOf(ad) + 1) * 3;
  // take up full row
  cell.setSpanSize(simpleRecyclerView.getGridSpanCount());
  cells.add(position, cell);
}

simpleRecyclerView.addCells(cells);

Cell Operations

SimpleRecyclerView provides basic CRUD cell operations.

Full cell operations list

It is common that loading cache data first and then fetch new data from network to update the list. The library provides addOrUpdateCell() and addOrUpdateCells() operation to achieve that (It uses DiffUtils under the hood). The cells will not be updated (i.e. receive onBindViewHolder() callback) if their bounded data models are the same, otherwsie they will be added to the end of list. To enable this feature, the cells must be implemented Updatable interface.

public interface Updatable<T> {

  boolean areContentsTheSame(T newItem);

  Object getChangePayload(T newItem);

}
public class BookCell extends SimpleCell<Book, BookCell.ViewHolder>
  implements Updatable<Book> {

  ...

  @Override
  protected void onBindViewHolder(ViewHolder holder, int position, Context context, Object payload) {
    if (payload != null) {
      // partial update
      if (payload instanceof Bundle) {
        Bundle bundle = ((Bundle) payload);
        for (String key : bundle.keySet()) {
          if (KEY_TITLE.equals(key)) {
            holder.textView.setText(bundle.getString(key));
          }
        }
      }
      return;
    }
    ...
  }
  
  /**
   * If the titles of books are same, no need to update the cell, onBindViewHolder() will not be called.
   */
  @Override
  public boolean areContentsTheSame(Book newItem) {
    return getItem().getTitle().equals(newItem.getTitle());
  }

  /**
   * If getItem() is the same as newItem (i.e. their return value of getItemId() are the same)
   * and areContentsTheSame()  return false, then the cell need to be updated,
   * onBindViewHolder() will be called with this payload object.
   * */
  @Override
  public Object getChangePayload(Book newItem) {
    Bundle bundle = new Bundle();
    bundle.putString(KEY_TITLE, newItem.getTitle());
    return bundle;
  }
  
  ...
}

Divider

<com.jaychang.srv.SimpleRecyclerView
    android:id="@+id/recyclerView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:srv_layoutMode="linearVertical" 
    app:srv_showDivider="true|false"
    app:srv_showLastDivider="true|false"
    app:srv_dividerOrientation="vertical|horizontal|both"
    app:srv_dividerColor="@color/your_color"
    app:srv_dividerPaddingLeft="dp"
    app:srv_dividerPaddingRight="dp"
    app:srv_dividerPaddingTop="dp"
    app:srv_dividerPaddingBottom="dp" />

Spacing

<com.jaychang.srv.SimpleRecyclerView
    android:id="@+id/recyclerView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:srv_layoutMode="linearVertical" 
    app:srv_spacing="dp"
    app:srv_verticalSpacing="dp"
    app:srv_horizontalSpacing="dp"
    app:srv_isSpacingIncludeEdge="true|false" />

Empty State View

The empty state view will be shown automatically when there is no data. If you want to show the empty state view explicitly, you can set srv_showEmptyStateView attribute to true (Default false).

<com.jaychang.srv.SimpleRecyclerView
    android:id="@+id/recyclerView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:srv_layoutMode="linearVertical" 
    app:srv_emptyStateView="@layout/view_empty_state" 
    app:srv_showEmptyStateView="true|false" />

Section Header

You can group cells together by providing a SectionHeaderProvider<T> to setSectionHeader(provider). A shorthand method SimpleSectionHeaderProvider<T> is also provided. The section header is not interative (e.g. can't be clicked)

SectionHeaderProvider<Book> sectionHeaderProvider = new SimpleSectionHeaderProvider<Book>() {
  // Your section header view here
  @NonNull
  @Override
  public View getSectionHeaderView(Book item, int position) {
    View view = LayoutInflater.from(SectionHeaderActivity.this).inflate(R.layout.view_section_header, null, false);
    TextView textView = (TextView) view.findViewById(R.id.textView);
    textView.setText(String.format(getString(R.string.category), item.getCategoryName()));
    return view;
  }
  // Your grouping logic here
  @Override
  public boolean isSameSection(Book item, Book nextItem) {
    return item.getCategoryId() == nextItem.getCategoryId();
  }

  // Optional, whether the header is sticky, default false
  @Override
  public boolean isSticky() {
    return stickyCheckbox.isChecked();
  }

  // Optional, top margin of each section header
  @Override
  public int getSectionHeaderMarginTop(Book item, int position) {
    return position == 0 ? 0 : Utils.dp2px(SectionHeaderActivity.this, 16);
  }
};

simpleRecyclerView.setSectionHeader(sectionHeaderProvider);

Auto Load More

Load more threshold

// if the total beneath hidden cells count <= 4 and shouldLoadMore() is true, onLoadMore() will be called. Default threshold is 0.
simpleRecyclerView.setAutoLoadMoreThreshold(4);

simpleRecyclerView.setOnLoadMoreListener(new OnLoadMoreListener() {
  @Override
  public boolean shouldLoadMore() {
    return hasMoreData;
  }
  
  @Override
  public void onLoadMore() {
    loadBooks();
  }
});

Load more view

<com.jaychang.srv.SimpleRecyclerView
    android:id="@+id/recyclerView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:srv_layoutMode="linearVertical"
    app:srv_loadMoreView="@layout/view_load_more" />

Load more to top

If you are going to build a list like chatting, i.e. the cells are added to top of the list, you should set setLoadMoreToTop(true). This instructs the SimpleRecyclerView to check threshold for the top hidden cells.

simpleRecyclerView.setLoadMoreToTop(true);

Drag & Drop

You can enable drag and drop by providing a DragAndDropCallback<T> for enableDragAndDrop(callback) or enableDragAndDrop(dragHandleResId, callback), the latter one accepts a drag handle view resource id, only pressing this view will trigger drag behavior. Default long press to trigger drag behavior. Also, all callback methods of DragAndDropCallback<T> are optional.

DragAndDropCallback<Book> dragAndDropCallback = new DragAndDropCallback<Book>() {
  // Optional, return false if you manipulate custom drag effect in the rest of callbacks.
  @Override
  public boolean enableDefaultRaiseEffect() {
    // default return true
    return super.enableDefaultRaiseEffect();
  }

  // Optional
  @Override
  public void onCellDragStarted(SimpleRecyclerView simpleRecyclerView, View itemView, Book item, int position) {
    resultView.setText("Started dragging " + item);
  }

  // Optional
  @Override
  public void onCellMoved(SimpleRecyclerView simpleRecyclerView, View itemView, Book item, int fromPosition, int toPosition){
    resultView.setText("Moved " + item + " from " + fromPosition + " to " + toPosition);
  }

  // Optional
  @Override
  public void onCellDropped(SimpleRecyclerView simpleRecyclerView, View itemView, Book item, int fromPosition, int toPosition) {
    resultView.setText("Dragged " + item + " from " + fromPosition + " to " + toPosition);
  }

  // Optional
  @Override
  public void onCellDragCancelled(SimpleRecyclerView simpleRecyclerView, View itemView, Book item, int currentPosition) {
    resultView.setText("Cancelled dragging " + item);
  }
};

simpleRecyclerView.enableDragAndDrop(R.id.dragHandle, dragAndDropCallback); 
// or
simpleRecyclerView.enableDragAndDrop(dragAndDropCallback);

Swipe To Dismiss

You can enable swipe to dismiss by providing a SwipeToDismissCallback<T> to enableSwipeToDismiss(callback, swipeDirections). All callback methods of SwipeToDismissCallback<T> are optional.

SwipeToDismissCallback<Book> swipeToDismissCallback = new SwipeToDismissCallback<Book>() {
  // Optional, return false if you manipulate custom swipe effect in the rest of callbacks.
  @Override
  public boolean enableDefaultFadeOutEffect() {
    // default return true
    return super.enableDefaultFadeOutEffect();
  }

  // Optional
  @Override
  public void onCellSwiping(SimpleRecyclerView simpleRecyclerView, View itemView, Book item, int position, Canvas canvas, float dX, float dY, boolean isControlledByUser) {
    resultView.setText("Item " + item + " is swiping.");
  }

  // Optional
  @Override
  public void onCellSettled(SimpleRecyclerView simpleRecyclerView, View itemView, Book item, int position) {
    resultView.setText("Item " + item + " is settled.");
  }

  // Optional
  @Override
  public void onCellDismissed(SimpleRecyclerView simpleRecyclerView, Book item, int position) {
    resultView.setText("Item: " + item + " is dismissed.");
  }
};

// enable swipe left or right to dismiss
simpleRecyclerView.enableSwipeToDismiss(swipeToDismissCallback, LEFT, RIGHT);

Snappy

<com.jaychang.srv.SimpleRecyclerView
   android:id="@+id/recyclerView"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   app:srv_layoutMode="linearHorizontal"
   app:srv_snappy="true|false"
   app:srv_snap_alignment="center|start" />