public final class SelectRecyclerAdapter extends RecyclerView.Adapter<SelectRecyclerAdapter.Holder> {
private int selectedPos = -1;
private ArrayList<String> dataList;
private OnSelectListener listener;
public FilterRecyclerAdapter(ArrayList<String> list, OnFilterClickListener callback) {
dataList = list;
listener = callback;
}
@Override
public FilterRecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_textview, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(Holder holder, int position) {
holder.textView.setText(dataList.get(position));
if (position == selectedPos) {
holder.textView.setBackgroundColor(Color.RED);
} else {
holder.textview.setBackgroundColor(Color.TRANSPARENT);
}
// You can use selector drawable resource and call holder.textView.setSelected(true or false);
}
@Override
public int getItemCount() {
return dataList.size();
}
class Holder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView textView;
Holder(View itemView) {
super(itemView);
textView = (TextView) itemView;
}
@Override
public void onClick(View view) {
if (listener == null) {
return;
}
int position = getAdapterPosition();
if (selectedPos == position) {
return;
}
selectedPos = position;
YourModel item = dataList.get(position);
listener.onSelect(getAdapterPosition(), item);
notifyDataSetChanged();
}
}
public void getSelectedPosition(){
return selectedPos;
}
public boolean hasSelection(){
return selectedPos != -1;
}
public interface OnSelectionListener {
void onSelect(int position, YourModel model);
}
}
This is a customized adapter for your RecyclerView implementation.
You may refer to online resources for examples of horizontal RecyclerView scrolling. Additionally, consider attaching LinearSnapHelper to the RecyclerView for an improved user experience.
Sample inflated layout :
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="48dp"
android:gravity="center"/>
If you intend to use View.setSelected(value), create a custom selector drawable with selectedState=true and no defined state items inside. Alternatively, set your shape to background instead using Color.RED;
Best of luck!
Emre