我有一个recyclerview。我想在点击项目时更改项目的背景。 使用我的代码更改了单击的项目,但滚动时,还有一些项目的背景也发生了变化,当向后滚动时,初始项目的背景更改回默认值。
这是我的适配器:
公共类MyCustomAdapter扩展了RecyclerView.Adapter {
private Context context;
private ArrayList<Information> data;
private LayoutInflater inflater;
private int previousPosition = 0;
private Resources resources;
private Drawable drawable;
public MyCustomAdapter(Context context, ArrayList<Information> data) {
this.context = context;
this.data = data;
inflater = LayoutInflater.from(context);
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int position) {
View view = inflater.inflate(R.layout.list_item_row, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(final MyViewHolder myViewHolder, final int position) {
myViewHolder.textView1.setText(data.get(position).title);
//myViewHolder.imageView.setImageResource(data.get(position).imageId);
if(position > previousPosition){ // We are scrolling DOWN
AnimationUtil.animate(myViewHolder, true);
}else{ // We are scrolling UP
AnimationUtil.animate(myViewHolder, false);
}
previousPosition = position;
final int currentPosition = position;
final Information infoData = data.get(position);
myViewHolder.cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(context, "Onlick Called at position "+position, Toast.LENGTH_LONG).show();
//myViewHolder.imageView.setImageResource(data.get(position).imageId);
resources = context.getResources();
drawable = resources.getDrawable(data.get(position).imageId);
myViewHolder.relativeLayout.setBackground(drawable);
}
});
}
@Override
public int getItemCount() {
return data.size();
}
class MyViewHolder extends RecyclerView.ViewHolder{
TextView textView1;
TextView textView2;
CardView cardView;
ImageView imageView;
RelativeLayout relativeLayout;
public MyViewHolder(View itemView) {
super(itemView);
textView1 = (TextView) itemView.findViewById(R.id.card_front_text1);
textView2 = (TextView) itemView.findViewById(R.id.card_front_text2);
imageView = (ImageView) itemView.findViewById(R.id.card_front_imageview);
relativeLayout = (RelativeLayout) itemView.findViewById(R.id.card_front_relativelayout);
cardView = (CardView) itemView.findViewById(R.id.cardView);
}
}
}
XML:
父级布局是Cardview,并且有一个相对布局子级。
答案 0 :(得分:1)
因为物料视图由RecyclerView重复使用。 在onBindViewHolder方法中,必须将项目视图设置为正确的状态。
答案 1 :(得分:1)
RecyclerView
将重复使用视图来填充数据。您应该保存单击视图的位置。在OnClickListener
保存位置:
myViewHolder.cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
clickedPosition = position;
......
}
});
在onBindViewHolder
中添加以下内容:
if (position == clickedPosition) {
resources = context.getResources();
drawable = resources.getDrawable(data.get(position).imageId);
myViewHolder.relativeLayout.setBackground(drawable);
} else {
myViewHolder.relativeLayout.setBackground(/* default background*/);
}