要实现只能单选的Android RecyclerView,可以通过以下步骤进行:
private int selectedItem = -1;
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView textView;
public MyViewHolder(View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.text_view);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
notifyItemChanged(selectedItem);
selectedItem = getAdapterPosition();
notifyItemChanged(selectedItem);
}
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.textView.setText(dataList.get(position));
if (position == selectedItem) {
holder.itemView.setBackgroundColor(Color.GRAY);
} else {
holder.itemView.setBackgroundColor(Color.WHITE);
}
}
这样,你的RecyclerView就只能单选了。点击一个item时,该item会高亮显示,并取消其他item的选中状态。