LoadStateAdapter


Adapter for displaying a RecyclerView item based on LoadState, such as a loading spinner, or a retry error button.

By default will use one shared view type for all items.

By default, both LoadState.Loading and LoadState.Error are presented as adapter items, other states are not. To configure this, override displayLoadStateAsItem.

To present this Adapter as a header and or footer alongside your PagingDataAdapter, see PagingDataAdapter.withLoadStateHeaderAndFooter, or use ConcatAdapter directly to concatenate Adapters.

class LoadStateViewHolder(
    parent: ViewGroup,
    retry: () -> Unit
) : RecyclerView.ViewHolder(
    LayoutInflater.from(parent.context)
        .inflate(R.layout.load_state_item, parent, false)
) {
    private val progressBar: ProgressBar = itemView.findViewById(R.id.progress_bar)
    private val errorMsg: TextView = itemView.findViewById(R.id.error_msg)
    private val retry: Button = itemView.findViewById<Button>(R.id.retry_button)
        .also { it.setOnClickListener { retry.invoke() } }

    fun bind(loadState: LoadState) {
        if (loadState is LoadState.Error) {
            errorMsg.text = loadState.error.localizedMessage
        }
        progressBar.visibility = toVisibility(loadState is LoadState.Loading)
        retry.visibility = toVisibility(loadState !is LoadState.Loading)
        errorMsg.visibility = toVisibility(loadState !is LoadState.Loading)
    }

    private fun toVisibility(constraint: Boolean): Int = if (constraint) {
        View.VISIBLE
    } else {
        View.GONE
    }
}

/**
 * Adapter which displays a loading spinner when `state = LoadState.Loading`, and an error
 * message and retry button when `state is LoadState.Error`.
 */
class MyLoadStateAdapter(
    private val retry: () -> Unit
) : LoadStateAdapter<LoadStateViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, loadState: LoadState) =
        LoadStateViewHolder(parent, retry)

    override fun onBindViewHolder(holder: LoadStateViewHolder, loadState: LoadState) =
        holder.bind(loadState)
}

Summary

Public constructors

android

Public functions

open Boolean

Returns true if the LoadState should be displayed as a list item when active.

android
final Int

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

android
final Int
getItemViewType(position: Int)

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

android
open Int

Override this method to use different view types per LoadState.

android
abstract Unit
onBindViewHolder(holder: VH, loadState: LoadState)

Called to bind the passed LoadState to the ViewHolder.

android
final Unit
onBindViewHolder(holder: VH, position: Int)

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

android
abstract VH
onCreateViewHolder(parent: ViewGroup, loadState: LoadState)

Called to create a ViewHolder for the given LoadState.

android
final VH
onCreateViewHolder(parent: ViewGroup, viewType: Int)

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

android

Public properties

LoadState

LoadState to present in the adapter.

android

Inherited functions

From androidx.recyclerview.widget.RecyclerView.Adapter
Unit
bindViewHolder(holder: VH, position: Int)

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.

android
VH
createViewHolder(parent: ViewGroup, viewType: Int)

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

android
open Int
findRelativeAdapterPositionIn(
    adapter: RecyclerView.Adapter<RecyclerView.ViewHolder>,
    viewHolder: RecyclerView.ViewHolder,
    localPosition: Int
)

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

android
open Long
getItemId(position: Int)

Return the stable ID for the item at position.

android
RecyclerView.Adapter.StateRestorationPolicy

Returns when this Adapter wants to restore the state.

android
Boolean

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

android
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.

android
Unit

Notify any registered observers that the data set has changed.

android
Unit

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

android
Unit
notifyItemChanged(position: Int, payload: Any?)

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

android
Unit

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

android
Unit
notifyItemMoved(fromPosition: Int, toPosition: Int)

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

android
Unit
notifyItemRangeChanged(positionStart: Int, itemCount: Int)

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

android
Unit
notifyItemRangeChanged(positionStart: Int, itemCount: Int, payload: Any?)

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

android
Unit
notifyItemRangeInserted(positionStart: Int, itemCount: Int)

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

android
Unit
notifyItemRangeRemoved(positionStart: Int, itemCount: Int)

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

android
Unit

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

android
open Unit

Called by RecyclerView when it starts observing this Adapter.

android
open Unit
onBindViewHolder(holder: VH, position: Int, payloads: MutableList<Any>)

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

android
open Unit

Called by RecyclerView when it stops observing this Adapter.

android
open Boolean

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

android
open Unit

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

android
open Unit

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

android
open Unit
onViewRecycled(holder: VH)

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

android
open Unit

Register a new observer to listen for data changes.

android
open Unit
setHasStableIds(hasStableIds: Boolean)

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

android
open Unit

Sets the state restoration strategy for the Adapter.

android
open Unit

Unregister an observer currently listening for data changes.

android

Public constructors

LoadStateAdapter

<VH : RecyclerView.ViewHolder> LoadStateAdapter()

Public functions

displayLoadStateAsItem

open fun displayLoadStateAsItem(loadState: LoadState): Boolean

Returns true if the LoadState should be displayed as a list item when active.

By default, LoadState.Loading and LoadState.Error present as list items, others do not.

getItemCount

final fun getItemCount(): Int

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

Returns
Int

The total number of items in this adapter.

getItemViewType

final fun getItemViewType(position: Int): Int

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

The default implementation of this method returns 0, making the assumption of a single view type for the adapter. Unlike ListView adapters, types need not be contiguous. Consider using id resources to uniquely identify item view types.

Parameters
position: Int

position to query

Returns
Int

integer value identifying the type of the view needed to represent the item at position. Type codes need not be contiguous.

getStateViewType

open fun getStateViewType(loadState: LoadState): Int

Override this method to use different view types per LoadState.

By default, this LoadStateAdapter only uses a single view type.

onBindViewHolder

abstract fun onBindViewHolder(holder: VH, loadState: LoadState): Unit

Called to bind the passed LoadState to the ViewHolder.

Parameters
loadState: LoadState

LoadState to display.

onBindViewHolder

final fun onBindViewHolder(holder: VH, position: Int): Unit

Called by RecyclerView to display the data at the specified position. This method should update the contents of the itemView to reflect the item at the given position.

Note that unlike android.widget.ListView, RecyclerView will not call this method again if the position of the item changes in the data set unless the item itself is invalidated or the new position cannot be determined. For this reason, you should only use the position parameter while acquiring the related data item inside this method and should not keep a copy of it. If you need the position of an item later on (e.g. in a click listener), use getBindingAdapterPosition which will have the updated adapter position. Override onBindViewHolder instead if Adapter can handle efficient partial bind.

Parameters
holder: VH

The ViewHolder which should be updated to represent the contents of the item at the given position in the data set.

position: Int

The position of the item within the adapter's data set.

onCreateViewHolder

abstract fun onCreateViewHolder(parent: ViewGroup, loadState: LoadState): VH

Called to create a ViewHolder for the given LoadState.

Parameters
parent: ViewGroup

The ViewGroup into which the new View will be added after it is bound to an adapter position.

loadState: LoadState

The LoadState to be initially presented by the new ViewHolder.

onCreateViewHolder

final fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH

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

This new ViewHolder should be constructed with a new View that can represent the items of the given type. You can either create a new View manually or inflate it from an XML layout file.

The new ViewHolder will be used to display items of the adapter using onBindViewHolder. Since it will be re-used to display different items in the data set, it is a good idea to cache references to sub views of the View to avoid unnecessary findViewById calls.

Parameters
parent: ViewGroup

The ViewGroup into which the new View will be added after it is bound to an adapter position.

viewType: Int

The view type of the new View.

Returns
VH

A new ViewHolder that holds a View of the given view type.

Public properties

loadState

var loadStateLoadState

LoadState to present in the adapter.

Changing this property will immediately notify the Adapter to change the item it's presenting.