我使用RecyclerView显示项目列表,我需要按位置更新单个项目的状态。我正在更新列表中的项目,然后像这样调用notifyItemChanged(int position):
myList.set(position, newModifiedItem);
notifyItemChanged(position);
项目已成功更新,但也会随机更新其他项目,每次我在项目列表中向上和向下滚动时,此更新(不同的图标状态)也会在其他项目上进行。
我在onBindViewHolder
进行更改,我逐个检查列表,并决定设置不同的状态。
完整适配器代码:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<MyObj> myList;
public MyAdapter(List<MyObj> list) {
this.myList = list;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_item, parent, false);
return new ViewHolder(view);
}
public void onBindViewHolder(final ViewHolder holder, final int position) {
MyObj myObj = myList.get(position);
boolean isSpecial = myObj.getMySpecialStatus();
holder.myItemTitle.setText(myObj.getTitle());
//decide if item has different icon state
if (isSpecial) {
holder.myItemIcon.setImageResource(R.drawable.ic_special);
}
}
@Override
public int getItemCount() {
return myList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView myItemTitle;
public ImageView myItemIcon;
public LinearLayout itemClickable;
//some other views
public ViewHolder(View itemView) {
super(itemView);
myItemTitle = (TextView) itemView.findViewById(R.id.item_title);
myItemIcon = (ImageView) itemView.findViewById(R.id.item_img);
itemClickable = (LinearLayout) itemView.findViewById(R.id.item_clickable_zone);
itemClickable.setOnClickListener(this);
//some other views
}
@Override
public void onClick(View v) {
final int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
switch (v.getId()) {
case R.id.item_clickable_zone: {
//some logic to change status - here just an idea
MyObj newModifiedItem = myList.get(position);
newModifiedItem.setMySpecialStatus(true);
myList.set(position, newModifiedItem);
notifyItemChanged(position);
break;
}
//some other views on click
}
}
}
}
}
答案 0 :(得分:2)
问题发生在onBindViewHolder()
,您没有对else
语句使用if
个案。它应该像:
public void onBindViewHolder(final ViewHolder holder, final int position) {
MyObj myObj = myList.get(position);
boolean isSpecial = myObj.getMySpecialStatus();
holder.myItemTitle.setText(myObj.getTitle());
//decide if item has different icon state
if (isSpecial) {
holder.myItemIcon.setImageResource(R.drawable.ic_special);
} else {
//here is the trick - set normal state back
holder.myItemIcon.setImageResource(R.drawable.ic_standard);
}
}
答案 1 :(得分:1)
试试这个,
MyObj newModifiedItem = myList.get(position); //getting object from the list
newModifiedItem.setMySpecialStatus(true);
notifyItemChanged(position, newModifiedItem);