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"
/>
There's a good documentation about these values: http://developer.android.com/reference/android/R.attr.html