Android Expand and collapse for recyclerview is not working as expected

1.3k Views Asked by At

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.

2

There are 2 best solutions below

1
Bhavin On

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
    }
});
....
2
private static On

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();
                }
            });
    }