Linked Questions

Popular Questions

RecyclerView generic adapter

Asked by At

Trying to create a generic adapter for the RecyclerView.
Already explored other solutions: RecyclerView generic adapter with DataBinding
Add click listener to Generic RecyclerView Adapter
https://github.com/ravirupareliya/Recyclerview-Generic-Adapter/blob/master/app/src/main/java/com/rrr/genericrecyclerview/adapter/RecyclerAdapter.java

However want to implement it in a bit different way.
Here is how my adapter looks like:

public abstract class GenericAdapter<T> extends RecyclerView.Adapter<BaseHolder<T>> {

    private OnRecyclerItemClickListener mListener;
    private List<T> mItems;
    private final LayoutInflater mLayoutInflater;

    public GenericAdapter(Context context) {
        mLayoutInflater =
                (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mItems = Collections.emptyList();
    }

    @Override
    public BaseHolder<T> onCreateViewHolder(ViewGroup parent, int viewType) {
        // assume that viewType is a resource id returned by getItemViewType 
        // also other solutions are welcome
        View view = mLayoutInflater.inflate(viewType, parent, false);

        // TODO: how to create the view holder ??
    }

    @Override
    public void onBindViewHolder(BaseHolder<T> holder, int position) {
        T item = mItems.get(position);
        holder.onBind(item, mListener);
    }

    @Override
    public int getItemCount() {
        return mItems != null ? mItems.size() : 0;
    }  

    public void setItems(List<T> items) {
        mItems = items;
        notifyDataSetChanged();
    }

    public void setItemClickListener(OnRecyclerItemClickListener listener) {
        mListener = listener;
    }
}

This is a base view holder from which I want to extend all other holders:

public abstract class BaseHolder<T> extends RecyclerView.ViewHolder {

    public BaseHolder(View itemView) {
        super(itemView);
    }

    public abstract void onBind(T item, OnRecyclerItemClickListener listener);
}

The problem is in onCreateViewHolder method.
How do I create the view holder?
Should I somehow implement abstract BaseHolder or should I somehow change the adapter class declaration extends i.e. instead BaseHolder here RecyclerView.Adapter> should be some generic implementation of BaseHolder? I tried > but it doesn't work

Thanks in advance for any piece of advice

Related Questions