Skip to content

Instantly share code, notes, and snippets.

@douglasdrumond
Forked from grantland/post.md
Created March 28, 2016 06:46
Show Gist options
  • Save douglasdrumond/408c36584aa6d249f08f to your computer and use it in GitHub Desktop.
Save douglasdrumond/408c36584aa6d249f08f to your computer and use it in GitHub Desktop.
RecyclerView item onClick

RecyclerView item onClick

RecyclerView does not have an OnItemClickListener like it's predecessor, ListView. However, detecting item clicks is pretty simple.

Set an OnClickListener in your ViewHolder creation:

private class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>  {

    public static class ViewHolder extends RecyclerView.ViewHolder
            implements View.OnClickListener {
        private String mItem;
        private TextView mTextView;

        public ViewHolder(View view) {
            super(view);
            view.setOnClickListener(this);
            mTextView = (TextView) view;
        }

        public void setItem(String item) {
            mItem = item;
            mTextView.setText(item);
        }

        @Override
        public void onClick(View view) {
            Log.d(TAG, "onClick " + getPosition() + " " + mItem);
        }
    }

    private String[] mDataset;

    public MyAdapter(String[] dataset) {
        mDataset = dataset;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.list_item, parent, false);
        ViewHolder vh = new ViewHolder(v);
        return vh;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.setItem(mDataset[position]);
    }

    @Override
    public int getItemCount() {
        return mDataset.length;
    }
}

Add touch feedback to your item layout:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceListItemSmall"
    android:gravity="center_vertical"
    android:paddingStart="?android:attr/listPreferredItemPaddingStart"
    android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
    android:minHeight="?android:attr/listPreferredItemHeightSmall"
    android:background="?android:attr/selectableItemBackground"
/>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment