Home > Net >  Android Expand and collapse for recyclerview is not working as expected
Android Expand and collapse for recyclerview is not working as expected

Time:12-16

I am developing an app with expandable Recyclerview. But expansion is not working as expected. Nothing works if I click on any item that is in collapsed state after expanding another item. I want to collapse the previously expanded item automatically if click any other item.

Please see my code for the same :

final boolean isExpanded = position==mExpandedPosition;
holder.expandableLayout.setVisibility(isExpanded?View.VISIBLE:View.GONE);
holder.itemView.setActivated(isExpanded);
if (isExpanded) {
    previousExpandedPosition = position;

}
holder.itemView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {



        mExpandedPosition = isExpanded ? -1:position;
        notifyItemChanged(previousExpandedPosition);
        notifyItemChanged(position);



    }
});

Please correct me if anything is wrong with my implementation.

CodePudding user response:

As i guess you're just notifying your current item that something has but not the older one which is already expanded which is causing the problem so apply changes as following.

....
holder.itemView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        int previousSelectedPosition = mExpandedPosition;
        mExpandedPosition = isExpanded ? -1:position;

        notifyItemChanged(position); // here we notified our current item   
        if (previousSelectedPosition != -1) 
           notifyItemChanged(previousSelectedPosition); // here we notified past item
    }
});
....

CodePudding user response:

You don't need a "previousExpandedPosition":

private int mExpandedPosition = -1;
@Override
    public void onBindViewHolder(MyAdapter.MyViewHolder holder, final int position) {
        String str = mData.get(position);
        holder.mText.setText(str);
        
        final boolean isExpanded = position == mExpandedPosition;
        holder.expandableLayout.setVisibility( isExpanded ? View.VISIBLE : View.GONE);
        holder.itemView.setActivated(isExpanded);
        holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mExpandedPosition = isExpanded ? -1 : position;
                    notifyDataSetChanged();
                }
            });
    }
  • Related