Skip to content

Instantly share code, notes, and snippets.

@cawfree
Last active March 19, 2018 10:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cawfree/9804c4f47f519e19a261f29ce537cc69 to your computer and use it in GitHub Desktop.
Save cawfree/9804c4f47f519e19a261f29ce537cc69 to your computer and use it in GitHub Desktop.
Heterogeneous Recycler Adapter; a simple way to define diverse RecyclerView content.
/**
* Created by Alexander Thomas (@Cawfree) on 03/07/2017.
*/
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.List;
/** A RecyclerAdapter that doesn't care about the data, or the views, it contains. That's left up to the caller. */
public class HeterogeneousAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
/* Member Variables. */
private final List<Element> mItems;
/** Constructor. */
public HeterogeneousAdapter(final List<Element> pItems) {
// Initialize Member Variables.
this.mItems = pItems;
}
/** Defines a heterogeneous element. */
public static abstract class Element {
/** Configures the binding methodology for the RecyclerView. */
public abstract void onBindViewHolder(final RecyclerView.ViewHolder pViewHolder);
/** Defines the ResourceId of the layout to use when inflating this Element. */
public abstract int getResourceId();
}
@Override
public final RecyclerView.ViewHolder onCreateViewHolder(final ViewGroup pViewGroup, final int pViewType) {
// Inflate the ResourceId indicated by the ViewType.
final View lView = LayoutInflater.from(pViewGroup.getContext()).inflate(pViewType, pViewGroup, false);
// Return the View wrapped as a ViewHolder.
return new RecyclerView.ViewHolder(lView) { /* Don't care. */ };
}
@Override
public final int getItemViewType(final int pPosition) {
// Fetch the ResourceId as the ViewType.
return this.getItems().get(pPosition).getResourceId();
}
@Override
public final void onBindViewHolder(final RecyclerView.ViewHolder pViewHolder, final int pPosition) {
// Fetch the Element.
this.getItems().get(pPosition).onBindViewHolder(pViewHolder);
}
@Override
public final int getItemCount() {
// Use the size of the items.
return this.getItems().size();
}
/* Getters. */
public final List<Element> getItems() {
return this.mItems;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment