我从食物项目列表中获得了Recyclerview。当您单击该项目时,我希望该项目显示为灰色。现在这确实有效,而我按下的第一个项目确实变灰了。然而,当我再次按下它时,其他一些细胞变成灰色。然后它变成了一个大混乱,随机的灰色变成灰色?
我已经设置了当你单击该项时,FoodItem实例有一个布尔值集。然后我刷新了recyclerview的数据,因此具有布尔值集的项目具有灰色覆盖。
这是我的适配器:
[
public class FoodAdapter extends RecyclerView.Adapter<FoodAdapter.MyViewHolder> {
ClickListener clickListener;
private List<FoodItem> foodList;
public void setClickListener(ClickListener clickListener) {
this.clickListener = clickListener;
}
public interface ClickListener {
void ItemClicked(View v, int position);
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView name;
public TextView quantity;
public RelativeLayout background;
public LinearLayout eatenOverlay;
public MyViewHolder(View view) {
super(view);
name = (TextView) view.findViewById(R.id.textView_item_name);
quantity = (TextView) view.findViewById(R.id.textView_item_quantity);
background = (RelativeLayout) view.findViewById(R.id.food_item_background_relative_layout);
eatenOverlay = (LinearLayout) view.findViewById(R.id.eaten_overlay);
}
}
public FoodAdapter(List<FoodItem> foodList) {
this.foodList = foodList;
}
@Override
public FoodAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.food_item_list, parent, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(FoodAdapter.MyViewHolder holder, final int position) {
FoodItem currentFoodItem = foodList.get(position);
if(currentFoodItem.isHasBeenEaten()){
holder.eatenOverlay.setVisibility(View.VISIBLE);
}
Resources res = holder.itemView.getContext().getResources();
holder.name.setText(currentFoodItem.getName());
holder.quantity.setText(currentFoodItem.getQuantity());
holder.background.setBackgroundResource(currentFoodItem.getImage());
holder.background.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (clickListener != null) {
clickListener.ItemClicked(v, position);
}
}
});
}
@Override
public int getItemCount() {
return foodList.size();
}
}
主要活动实现了界面,所以当点击项目时,在主要活动中我有这个代码;
@Override
public void ItemClicked(View v, int position) {
foodList.get(position).setHasBeenEaten(true);
Log.d(TAG,foodList.get(position).getName() + " clicked");
Log.d(TAG,"position: " + position);
mAdapter.notifyDataSetChanged();
}
为什么会这样?感谢
答案 0 :(得分:3)
你只是错过了另一种选择。
場所 バショ バショ 場所 名詞-普通名詞-一般
需要一个else分支,否则由于回收,您可以重复使用之前的“配置”前一个视图。