Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to select and de-select an item in RecyclerView? How to Highlight selected item only in recycler view?

@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. I have a recycler view where I need to select only one item, so on that basis, I have to show a sub list items.

  2. Now the problem is when I unselect that item the below sub list items should be hidden.

  3. Please suggest me an answer I will be thankful for the answer.

like image 262
arjun Avatar asked Jun 15 '18 09:06

arjun


1 Answers

Here is the solution for your requirement

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

        @Override
        public void onBindViewHolder(AdapterClass.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

     }


}
like image 54
Quick learner Avatar answered Sep 28 '22 09:09

Quick learner