Skip to content
This repository has been archived by the owner on May 1, 2020. It is now read-only.

Using SquidRecyclerAdapter

Sam Bosley edited this page Aug 24, 2016 · 10 revisions

SquidRecyclerAdapter is an implementation of RecyclerView.Adapter that wraps a SquidCursor.

Constructing a SquidRecyclerAdapter

SquidRecyclerAdapter is an abstract class. Implementations of SquidRecyclerAdapter are paired with an implementation of SquidViewHolder -- a ViewHolder that also holds a reusable model instance. For example:

public class PersonViewHolder extends SquidViewHolder<Person> {
    public PersonViewHolder(View itemView) {
        super(itemView, new Person());
    }
 }

The SquidRecyclerAdapter itself has two constructor options -- a no-arg constructor and a constructor that takes an id column. If an id column is provided, it will be used to implement getItemId() and the adapter will return true for hasStableIds(). Implementers must also override onCreateViewHolder (as usual for RecyclerView.Adapters) and onBindSquidViewHolder (in place of the standard onBindViewHolder).

public class PersonAdapter extends SquidRecyclerAdapter<Person, PersonViewHolder> {

    public PersonAdapter() {
        super(Person.ID); // Use this id column for getItemId()
    }

    @Override
    public PersonViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = createView(parent, viewType); // Create your view here
        return new PersonViewHolder(view);
    }

    @Override
    public void onBindSquidViewHolder(PersonViewHolder holder, int position) {
        // Item will be populated for values at position
        Person person = holder.item;

        // Populate view
    }
}

Populating the adapter with data

To populate the adapter with data, call swapCursor() with an instance of SquidCursor:

PersonAdapter adapter = new PersonAdapter(context);
SquidCursor<Person> cursor = ...;
adapter.swapCursor(cursor);

If you are calling swapCursor() to populate the adapter from LoaderCallbacks.onLoadFinished(), you are encouraged to call swapCursor(null) in onLoaderReset().

Adding SquidRecyclerAdapter as a dependency

SquidRecyclerAdapter is available as a separate add-on module, which you will need to add as a dependency in your build.gradle:

dependencies {
    compile 'com.yahoo.squidb:squidb-recyclerview:3.1.2'
}

Note that squidb-recyclerview includes a dependency on the Android support library (recyclerview-v7). If you want to force a particular version of the support library to be used in your own project, you should exclude this transitive dependency. For example:

dependencies {
    compile('com.yahoo.squidb:squidb-recyclerview:3.1.2') {
        exclude module: 'recyclerview-v7' // Exclude the support lib dependency by module name
    }
}

There are various other gradle strategies to exclude transitive dependencies as documented here.


See also: