我有一個食品項目列表中的recyclerview。當您點擊該項目時,我希望該項目變灰。現在,這確實奏效,而我按下的第一個項目確實變成了灰色。但是當我再次按下它時,其他一些單元格變成灰色。然後它變成了一個大混亂,隨機的灰色?RecyclerView onBindViewHolder單擊監聽器更改錯誤單元格的內容
我已經設置它,當你點擊該項目時,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();
}
}
和主要活動實現的接口,所以在單擊項目時,在主acitivty我有這樣的代碼;
@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();
}
這是怎麼發生的?謝謝
您應該在ViewHolder類中實現onclick監聽器,並從getAdapterPosiotion()獲取位置; https://developer.android.com/reference/android/support/v7/widget/RecyclerView.ViewHolder.html#getAdapterPosition() –