如何选择和取消选择RecyclerView中的项目?

时间:2018-06-15 09:08:59

标签: android android-recyclerview background-color

@Override
    public void onBindViewHolder(final mainscreenspecializationadap.MyViewHolder holder, final int positionz) {
        this.position = holder.getAdapterPosition();
        final specializationpojo album = albumList.get(holder.getAdapterPosition());
        holder.txtspecs.setText(album.getSplztnname());
        holder.imgspecs.setImageResource(album.getIcon());

    holder.linelayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            row_index=positionz;
            album.setOpened(!album.isOpened());
            notifyDataSetChanged();

        }
    });
    if(positionz==row_index){
        holder.imageView.setBackground(mContext.getResources().getDrawable(R.drawable.white_circle_background));
        holder.txtspecs.setSelected(true);
        if (type==1)
        {
            onClick.onSelected(row_index,album.isOpened(),album.isClosed());
        }
        else if(type==2)
        {   onClick.onSpecialisationSelected(album.getSplzcode(),album.getCount());
        }
    }
    else
    {
        holder.txtspecs.setSelected(false);
        holder.imageView.setBackground(mContext.getResources().getDrawable(R.drawable.green_background));
    }

}
  1. 我有一个回收站视图,我只需要选择一个项目,所以在此基础上,我必须显示一个子列表项目。

  2. 现在的问题是当我取消选择该项目时,应隐藏以下子列表项目。

  3. 请给我一个答案我会感谢答案。

1 个答案:

答案 0 :(得分:5)

以下是您的要求的解决方案

    public class AdapterClass extends RecyclerView.Adapter<AdapterClass.ViewHolder> {
        private int selected_position = -1;

        @Override
        public void onBindViewHolder(PlacesLocationAdapter.ViewHolder holder, final int position) {
            if (selected_position == position) {
                // do your stuff here like
                //Change selected item background color and Show sub item views

            } else {
                  // do your stuff here like
                  //Change  unselected item background color and Hide sub item views
            }
  // rest of the code here

    holder.linelayout.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View view) {
              if(selected_position==position){
                        selected_position=-1;
                        notifyDataSetChanged();
                        return;
                    }
                    selected_position = position;
                    notifyDataSetChanged();

            }
        });

    //rest of the code here

     }


}