kalehv
5/3/2017 - 3:08 PM

RecyclerViewAdapter

RecyclerViewAdapter

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
  // I like this name better because list items (view holders) are now 
  // free to have more types of interaction and not just click.
  interface OnItemInteractionListener {
    void OnItemClick(View view, int position);
  }
  
  private OnItemInteractionListener mListener;
  
  public void setOnItemInteractionListener(OnItemInteractionListener listener) {
    this.mListener = listener;
  }
  
  public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    // This may be required required if ViewHolder is inner static class of RecyclerAdapter
    // private RecyclerViewClickListener mListener;

    ViewHolder(View v) {
        super(v);
        v.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
      int position = getAdapterPosition();
      
      if (mListener != null && position != RecyclerView.NO_POSITION) {
        mListener.onClick(view, getAdapterPosition());
      }
    }
  }
}