通过Recyclerview仅选择一个图像

时间:2017-05-01 07:59:40

标签: java android android-recyclerview

在recyclerview项目中,我只需选择一个并使其背景为白色并取消选择前一个。

public class viewHolder extends RecyclerView.ViewHolder {

        TextView periodCategoryName;
        ImageView periodCategoryPhoto;
        View dottedLine;

        public viewHolder(View itemView) {
            super(itemView);

            periodCategoryPhoto=(ImageView) itemView.findViewById(R.id.mood_icon);

            periodCategoryPhoto.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Log.i("Get Adapeter position ",Integer.toString(getAdapterPosition()));

                    selectedPosition=getAdapterPosition();
                    notifyItemRangeChanged(0,periodListPhoto.size()-1);
                }
            });

        }
    }
 @Override
    public void onBindViewHolder(final PeriodListAdaptor.viewHolder holder, final int position) {

    holder.periodCategoryPhoto.setImageResource(periodListPhoto.get(position));


        //only one period item is highlighted
        if(selectedPosition == position){
            //already selected item
            Log.i("Selected position is ",Integer.toString(selectedPosition));
            holder.periodCategoryPhoto.setBackground(ContextCompat.getDrawable(mContext,R.drawable.item_selected));
        }else{
            //do nothing
        }



    }

我得到了奇怪的行为。有时在选择新项目时取消选择先前选择的项目。有时两者都被选中。

1 个答案:

答案 0 :(得分:0)

ViewHolder正在被重复使用,这意味着您应该处理onBindViewHolder()中的两种情况:

if (selectedPosition == position) {
    ...
} else {
    holder.periodCategoryPhoto.setBackground(defaultBagroundColor);
}