我有一个RecycleView显示一堆列表,其中一个项目通过显示其背景颜色为蓝色来选择,现在我希望用户从列表中选择任何项目,其颜色变为蓝色如何在RecyclerView中实现此项目。适配器或任何其他逻辑
public class ToggleAdapter extends RecyclerView.Adapter<ToggleAdapter.ToggleViewHolder>{
private ArrayList<ToggleParams> dataList=new ArrayList<>();
private Context context;
private static int selection;
public ToggleAdapter(ArrayList<ToggleParams> dataList, Context context,int selection) {
setData(dataList,context,selection);
}
@Override
public ToggleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view_row,parent,false);
ToggleViewHolder toggleViewHolder=new ToggleViewHolder(v);
return toggleViewHolder;
}
@Override
public void onBindViewHolder(ToggleViewHolder holder, int position) {
if(position==selection){
holder.selected_item.setBackgroundColor(context.getResources().getColor(R.color.blue));
holder.text_view.setTextColor(context.getResources().getColor(android.R.color.white));
}
holder.image_view.setImageDrawable(context.getResources().getDrawable(dataList.get(position).getIMAGE_ID()));
holder.text_view.setText(dataList.get(position).getTOGGLE_TEXT());
}
private void setData(ArrayList<ToggleParams> dataList, Context context,int selection) {
this.dataList = dataList;
this.context = context;
this.selection = selection;
}
@Override
public int getItemCount() {
return dataList.size();
}
public static class ToggleViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public LinearLayout selected_item;
public ImageView image_view;
public TextView text_view;
public ToggleViewHolder(View itemView) {
super(itemView);
selected_item= (LinearLayout) itemView.findViewById(R.id.selected_item);
selected_item.setOnClickListener(this);
image_view= (ImageView) itemView.findViewById(R.id.imageView);
text_view= (TextView) itemView.findViewById(R.id.textView);
}
public void onClick(View v) {
selection=getPosition();
//After getting this position I want that this item list in recyclerview to change its background color but how to call notifyDataSetChange() here something equivalent to that
}
}
}
答案 0 :(得分:0)
您可以使用setOnCLickListener
中的onBindViewHolder
并在那里调用notifyDatasetChanged
,或者更好的方法是定义一个在单击itemView时调用的接口并在其中实例化它适配器。例如,请参阅以下答案
Why doesn't RecyclerView have onItemClickListener()? And how RecyclerView is different from Listview?