ListAdapter


public abstract class ListAdapter<T, VH extends RecyclerView.ViewHolder> extends RecyclerView.Adapter


RecyclerView.Adapter base class for presenting List data in a RecyclerView, including computing diffs between Lists on a background thread.

This class is a convenience wrapper around AsyncListDiffer that implements Adapter common default behavior for item access and counting.

While using a LiveData is an easy way to provide data to the adapter, it isn't required - you can use submitList when new lists are available.

A complete usage pattern with Room would look like this:

@Dao
interface UserDao {
    @Query("SELECT * FROM user ORDER BY lastName ASC")
    public abstract LiveData<List<User>> usersByLastName();
}

class MyViewModel extends ViewModel {
    public final LiveData<List<User>> usersList;
    public MyViewModel(UserDao userDao) {
        usersList = userDao.usersByLastName();
    }
}

class MyActivity extends AppCompatActivity {
    @Override
    public void onCreate(Bundle savedState) {
        super.onCreate(savedState);
        MyViewModel viewModel = new ViewModelProvider(this).get(MyViewModel.class);
        RecyclerView recyclerView = findViewById(R.id.user_list);
        UserAdapter<User> adapter = new UserAdapter();
        viewModel.usersList.observe(this, list -> adapter.submitList(list));
        recyclerView.setAdapter(adapter);
    }
}

class UserAdapter extends ListAdapter<User, UserViewHolder> {
    public UserAdapter() {
        super(User.DIFF_CALLBACK);
    }
    @Override
    public void onBindViewHolder(UserViewHolder holder, int position) {
        holder.bindTo(getItem(position));
    }
    public static final DiffUtil.ItemCallback<User> DIFF_CALLBACK =
            new DiffUtil.ItemCallback<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);
        }
    }
}
Advanced users that wish for more control over adapter behavior, or to provide a specific base class should refer to AsyncListDiffer, which provides custom mapping from diff events to adapter positions.
Parameters
<T>

Type of the Lists this Adapter will receive.

<VH extends RecyclerView.ViewHolder>

A class that extends ViewHolder that will be used by the adapter.

Summary

Protected constructors

Public methods

@NonNull List<T>

Get the current List - any diffing to present this list has already been computed and dispatched via the ListUpdateCallback.

int

Returns the total number of items in the data set held by the adapter.

void
onCurrentListChanged(
    @NonNull List<T> previousList,
    @NonNull List<T> currentList
)

Called when the current List is updated.

void

Submits a new list to be diffed, and displayed.

void
submitList(@Nullable List<T> list, @Nullable Runnable commitCallback)

Set the new list to be displayed.

Protected methods

T
getItem(int position)

Inherited methods

From androidx.recyclerview.widget.RecyclerView.Adapter
final void
bindViewHolder(@NonNull VH holder, int position)

This method internally calls onBindViewHolder to update the ViewHolder contents with the item at the given position and also sets up some private fields to be used by RecyclerView.

final @NonNull VH
createViewHolder(@NonNull ViewGroup parent, int viewType)

This method calls onCreateViewHolder to create a new ViewHolder and initializes some private fields to be used by RecyclerView.

int
findRelativeAdapterPositionIn(
    @NonNull RecyclerView.Adapter<RecyclerView.ViewHolder> adapter,
    @NonNull RecyclerView.ViewHolder viewHolder,
    int localPosition
)

Returns the position of the given ViewHolder in the given Adapter.

long
getItemId(int position)

Return the stable ID for the item at position.

int
getItemViewType(int position)

Return the view type of the item at position for the purposes of view recycling.

final @NonNull RecyclerView.Adapter.StateRestorationPolicy

Returns when this Adapter wants to restore the state.

final boolean

Returns true if one or more observers are attached to this adapter.

final boolean

Returns true if this adapter publishes a unique long value that can act as a key for the item at a given position in the data set.

final void

Notify any registered observers that the data set has changed.

final void
notifyItemChanged(int position)

Notify any registered observers that the item at position has changed.

final void
notifyItemChanged(int position, @Nullable Object payload)

Notify any registered observers that the item at position has changed with an optional payload object.

final void
notifyItemInserted(int position)

Notify any registered observers that the item reflected at position has been newly inserted.

final void
notifyItemMoved(int fromPosition, int toPosition)

Notify any registered observers that the item reflected at fromPosition has been moved to toPosition.

final void
notifyItemRangeChanged(int positionStart, int itemCount)

Notify any registered observers that the itemCount items starting at position positionStart have changed.

final void
notifyItemRangeChanged(
    int positionStart,
    int itemCount,
    @Nullable Object payload
)

Notify any registered observers that the itemCount items starting at position positionStart have changed.

final void
notifyItemRangeInserted(int positionStart, int itemCount)

Notify any registered observers that the currently reflected itemCount items starting at positionStart have been newly inserted.

final void
notifyItemRangeRemoved(int positionStart, int itemCount)

Notify any registered observers that the itemCount items previously located at positionStart have been removed from the data set.

final void
notifyItemRemoved(int position)

Notify any registered observers that the item previously located at position has been removed from the data set.

void

Called by RecyclerView when it starts observing this Adapter.

abstract void
onBindViewHolder(@NonNull VH holder, int position)

Called by RecyclerView to display the data at the specified position.

void
onBindViewHolder(
    @NonNull VH holder,
    int position,
    @NonNull List<Object> payloads
)

Called by RecyclerView to display the data at the specified position.

abstract @NonNull VH
onCreateViewHolder(@NonNull ViewGroup parent, int viewType)

Called when RecyclerView needs a new ViewHolder of the given type to represent an item.

void

Called by RecyclerView when it stops observing this Adapter.

boolean

Called by the RecyclerView if a ViewHolder created by this Adapter cannot be recycled due to its transient state.

void

Called when a view created by this adapter has been attached to a window.

void

Called when a view created by this adapter has been detached from its window.

void
onViewRecycled(@NonNull VH holder)

Called when a view created by this adapter has been recycled.

void

Register a new observer to listen for data changes.

void
setHasStableIds(boolean hasStableIds)

Indicates whether each item in the data set can be represented with a unique identifier of type java.lang.Long.

void

Sets the state restoration strategy for the Adapter.

void

Unregister an observer currently listening for data changes.

Protected constructors

ListAdapter

Added in 1.0.0
protected ListAdapter(@NonNull AsyncDifferConfig<T> config)

ListAdapter

Added in 1.0.0
protected ListAdapter(@NonNull DiffUtil.ItemCallback<T> diffCallback)

Public methods

getCurrentList

Added in 1.1.0
public @NonNull List<T> getCurrentList()

Get the current List - any diffing to present this list has already been computed and dispatched via the ListUpdateCallback.

If a null List, or no List has been submitted, an empty list will be returned.

The returned list may not be mutated - mutations to content must be done through submitList.

Returns
@NonNull List<T>

The list currently being displayed.

getItemCount

Added in 1.4.0-rc01
public int getItemCount()

Returns the total number of items in the data set held by the adapter.

Returns
int

The total number of items in this adapter.

onCurrentListChanged

Added in 1.1.0
public void onCurrentListChanged(
    @NonNull List<T> previousList,
    @NonNull List<T> currentList
)

Called when the current List is updated.

If a null List is passed to submitList, or no List has been submitted, the current List is represented as an empty List.

Parameters
@NonNull List<T> previousList

List that was displayed previously.

@NonNull List<T> currentList

new List being displayed, will be empty if null was passed to submitList.

See also
getCurrentList

submitList

Added in 1.0.0
public void submitList(@Nullable List<T> list)

Submits a new list to be diffed, and displayed.

If a list is already being displayed, a diff will be computed on a background thread, which will dispatch Adapter.notifyItem events on the main thread.

Parameters
@Nullable List<T> list

The new list to be displayed.

submitList

Added in 1.1.0
public void submitList(@Nullable List<T> list, @Nullable Runnable commitCallback)

Set the new list to be displayed.

If a List is already being displayed, a diff will be computed on a background thread, which will dispatch Adapter.notifyItem events on the main thread.

The commit callback can be used to know when the List is committed, but note that it may not be executed. If List B is submitted immediately after List A, and is committed directly, the callback associated with List A will not be run.

Parameters
@Nullable List<T> list

The new list to be displayed.

@Nullable Runnable commitCallback

Optional runnable that is executed when the List is committed, if it is committed.

Protected methods

getItem

Added in 1.0.0
protected T getItem(int position)