Hello.
I want to implement single item selection function in RecyclerView
RecyclerView
's item is made up of TextView
only.
When i clicked items, i want to change TextView
's background color
I want to click only single item.
But items are clicked only multiple
When I click the first item and then the second item, the background color of the first item should be changed.
This is i wanted.
However i can't change the Text
of the previous item in 'Adapter'.
I don't know how to get previous selected View
.
How should i do?
Adapter.java
public class RoutineListAdapter extends RecyclerView.Adapter<RoutineListAdapter.ViewHolder> {
// ArrayList<RoutineListModel> items;
List<String> items = new ArrayList<>();
Context context;
public void addItems(List<String> items) {
this.items = items;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View itemView = inflater.inflate(R.layout.routine_list_item, parent, false);
return new ViewHolder(itemView);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
holder.setItem(items.get(position));
}
@Override
public int getItemCount() {
return items.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView routine;
boolean isSelected;
public ViewHolder(@NonNull View itemView) {
super(itemView);
routine = itemView.findViewById(R.id.routine_list);
routine.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(isSelected == false) {
routine.setBackgroundColor(context.getResources().getColor(R.color.light_green_dark));
isSelected = true;
}
else {
routine.setBackgroundColor(context.getResources().getColor(R.color.white));
isSelected = false;
}
}
});
}
private void setItem(String item) {
routine.setText(item);
}
}
}
question from:
https://stackoverflow.com/questions/65646437/android-how-to-select-singleitem-in-recyclerview 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…