在recyclerview项目上更改背景颜色也会更改列表中下面几个视图中的颜色

时间:2016-10-12 18:41:32

标签: android

我处理列表项的点击的方式是我在ViewHolder类上实现(OnClickListener,OnLongClickListener),我定义了所需的方法,一切正常。当我长按我设置该视图的背景颜色,它工作正常。现在的问题是,我怀疑因为回收者视图重用视图的方式,当我向下滚动列表时,还有另一个视图也改变了它的背景颜色,例如,如果我长按项目#2,项目#13将也改变它的背景颜色。

这是我的观点持有者类:

 private class CrimeViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {
        private TextView mCrimeTitle;
        private TextView mCrimeDate;
        private CheckBox mCrimeSolved;
        private View mView;

        @Override
        public boolean onLongClick(View v) {

            mMenu.findItem(R.id.menu_item_delete_crime).setVisible(true);
            isLongClicked = true;
            mSelectedItem = getAdapterPosition();
            v.setBackgroundColor(Color.parseColor("#6A6160"));
            return true;
        }

        @Override
        public void onClick(View v) {

            if(isLongClicked == true){

                mMenu.findItem(R.id.menu_item_delete_crime).setVisible(false);
                mLayoutManager.findViewByPosition(mSelectedItem).setBackgroundColor(Color.parseColor("#E0E0E0"));
                isLongClicked = false;
            }
            else{

            Intent intent = new Intent(getActivity(), CrimePagerActivity.class);
            //intent.putExtra(CRIME_ID_EXTRA, mCrimes.get(getAdapterPosition()).getmCrimeID());
            intent.putExtra(CRIME_POSITION_EXTRA, getAdapterPosition());
            startActivity(intent); }
        }

        public CrimeViewHolder(View view){
             super(view);
             mView = view;
             view.setOnClickListener(this);
             view.setOnLongClickListener(this);
             mCrimeTitle = (TextView) view.findViewById(R.id.list_crime_title);
             mCrimeDate = (TextView) view.findViewById(R.id.list_crime_date);
             mCrimeSolved = (CheckBox) view.findViewById(R.id.list_crime_solved);

             mCrimeSolved.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                 @Override
                 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                     mCrimes.get(getAdapterPosition()).setmSolved(isChecked);
                 }
             });


        }
    }

OnBindViewHolder代码:

 public void onBindViewHolder(CrimeViewHolder holder, int position) {

            holder.mCrimeTitle.setText(mCrimes.get(position).getmTitle());
            holder.mCrimeDate.setText(mCrimes.get(position).getmDate().toString("dd-MM-yyyy"));
            holder.mCrimeSolved.setChecked(mCrimes.get(position).ismSolved());

        }

0 个答案:

没有答案