在我的應用程序中,我有水平列表視圖。在項目選擇我想要更改選定的項目背景顏色和它的文本視圖顏色。我已經想出了那部分。但是如何重置先前選擇的項目的背景顏色和文本視圖顏色。這是我的適配器類。如何更改列表項目點擊的項目外觀。
public class DateRangeListViewAdapter extends RecyclerView.Adapter<DateRangeListViewAdapter.ContentViewHolder> {
private ItemClickListener itemClickListener;
private LayoutInflater inflater;
private ArrayList<String> data;
private Context context;
private int dataType;
private int previousSelectedPosition;
private static final int DATE_TYPE = 1;
private static final int STATUS_TYPE = 2;
public DateRangeListViewAdapter(ArrayList<String> data, Context context,int dataType) {
this.data = data;
this.context = context;
this.dataType = dataType;
inflater = LayoutInflater.from(context);
previousSelectedPosition = -1;
}
public void setItemClickListener(ItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
@Override
public ContentViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.custom_date_range_list_item,parent,false);
return new ContentViewHolder(view);
}
@Override
public void onBindViewHolder(ContentViewHolder holder, int position) {
String name = data.get(position);
holder.dateText.setText(name);
}
@Override
public int getItemCount() {
return data.size();
}
public class ContentViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private FrameLayout main;
private TextView dateText;
public ContentViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
main = (FrameLayout) itemView.findViewById(R.id.main_layout);
dateText = (TextView) itemView.findViewById(R.id.date_name);
}
@Override
public void onClick(View v) {
//Selected item color change
main.setBackground(ContextCompat.getDrawable(context,R.drawable.date_range_selected_item_background));
dateText.setTextColor(ContextCompat.getColor(context,R.color.colorPrimary));
if(itemClickListener!=null){
itemClickListener.onItemClick(v,this.getLayoutPosition(),dataType,getOldPosition());
}
}
}
public interface ItemClickListener{
public void onItemClick(View v, int position,int dataType,int oldPosition);
}
}
您應該在代碼中指明需要重置背景的位置。 –
對項目點擊查看裏面'ContentViewHolder'視圖持有者類 –
在設置背景和文本顏色之前調用'notifyDataSetChanged' –