create a RecyclerView grid divider item decoration in Android t

·

1 min read

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.LayoutRes;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;

public abstract class GenericAdapter<T, D> extends RecyclerView.Adapter<GenericAdapter.ViewHolder> {

    private Context mContext;
    private ArrayList<T> mArrayList;

    public GenericAdapter(Context context, ArrayList<T> arrayList) {
        this.mContext = context;
        this.mArrayList = arrayList;
    }

    public abstract int getViewType(int position, T model);

    public abstract int getLayoutResId(int viewType);

    public abstract void onBindData(T model, int position, D dataBinding);

    public abstract void onItemClick(T model, int position);

    @Override
    public int getItemViewType(int position) {
        return getViewType(position, mArrayList.get(position));
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext()).inflate(getLayoutResId(viewType), parent, false);
        ViewDataBinding dataBinding = DataBindingUtil.bind(itemView);
        return new ViewHolder(dataBinding);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        onBindData(mArrayList.get(position), position, holder.getDataBinding());

        holder.itemView.setOnClickListener(view -> onItemClick(mArrayList.get(position), position));
    }

    @Override
    public int getItemCount() {
        return mArrayList.size();
    }

    public void addItems(ArrayList<T> arrayList) {
        mArrayList = arrayList;
        notifyDataSetChanged();
    }

    public T getItem(int position) {
        return mArrayList.get(position);
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        private D mDataBinding;

        public ViewHolder(View itemView) {
            super(itemView);
            mDataBinding = DataBindingUtil.bind(itemView);
        }

        public D getDataBinding() {
            return mDataBinding;
        }
    }
}