[android] RecyclerView expand/collapse items

There is simply no need of using third party libraries. A little tweak in the method demonstrated in Google I/O 2016 and Heisenberg on this topic, does the trick.

Since notifyDataSetChanged() redraws the complete RecyclerView, notifyDataItemChanged() is a better option (not the best) because we have the position and the ViewHolder at our disposal, and notifyDataItemChanged() only redraws the particular ViewHolder at a given position.

But the problem is that the premature disappearence of the ViewHolder upon clicking and it's emergence is not eliminated even if notifyDataItemChanged() is used.

The following code does not resort to notifyDataSetChanged() or notifyDataItemChanged() and is Tested on API 23 and works like a charm when used on a RecyclerView where each ViewHolder has a CardView as it's root element:

holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final boolean visibility = holder.details.getVisibility()==View.VISIBLE;

            if (!visibility)
            {
                holder.itemView.setActivated(true);
                holder.details.setVisibility(View.VISIBLE);
                if (prev_expanded!=-1 && prev_expanded!=position)
                {
                    recycler.findViewHolderForLayoutPosition(prev_expanded).itemView.setActivated(false);
                    recycler.findViewHolderForLayoutPosition(prev_expanded).itemView.findViewById(R.id.cpl_details).setVisibility(View.GONE);
                }
                prev_expanded = position;
            }
            else
            {
                holder.itemView.setActivated(false);
                holder.details.setVisibility(View.GONE);
            }
            TransitionManager.beginDelayedTransition(recycler);              
        }
});

prev_position is an global integer initialized to -1. details is the complete view which is shown when expanded and cloaked when collapsed.

As said, the root element of ViewHolder is a CardView with foreground and stateListAnimator attributes defined exactly as said by Heisenberg on this topic.

UPDATE: The above demonstration will collapse previosuly expanded item if one of them in expanded. To modify this behaviour and keep the an expanded item as it is even when another item is expanded, you'll need the following code.

if (row.details.getVisibility()!=View.VISIBLE)
    {
        row.details.setVisibility(View.VISIBLE);
        row.root.setActivated(true);
        row.details.animate().alpha(1).setStartDelay(500);
    }
    else
    {
        row.root.setActivated(false);
        row.details.setVisibility(View.GONE);
        row.details.setAlpha(0);
    }
    TransitionManager.beginDelayedTransition(recycler);

UPDATE: When expanding the last items on the list, it may not be brought into full visibility because the expanded portion goes below the screen. To get the full item within screen use the following code.

LinearLayoutManager manager = (LinearLayoutManager) recycler.getLayoutManager();
    int distance;
    View first = recycler.getChildAt(0);
    int height = first.getHeight();
    int current = recycler.getChildAdapterPosition(first);
    int p = Math.abs(position - current);
    if (p > 5) distance = (p - (p - 5)) * height;
    else       distance = p * height;
    manager.scrollToPositionWithOffset(position, distance);

IMPORTANT: For the above demonstrations to work, one must keep in their code an instance of the RecyclerView & it's LayoutManager (the later for flexibility)

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to android-layout

How to check if a key exists in Json Object and get its value How to center the elements in ConstraintLayout Android - how to make a scrollable constraintlayout? Add ripple effect to my button with button background color? This view is not constrained vertically. At runtime it will jump to the left unless you add a vertical constraint Is it possible to put a ConstraintLayout inside a ScrollView? Differences between ConstraintLayout and RelativeLayout How to remove title bar from the android activity? How to have EditText with border in Android Lollipop Android: ScrollView vs NestedScrollView

Examples related to android-recyclerview

Failed to resolve: com.android.support:cardview-v7:26.0.0 android CardView background color always white Changing background color of selected item in recyclerview Simple Android grid example using RecyclerView with GridLayoutManager (like the old GridView) Simple Android RecyclerView example Android Horizontal RecyclerView scroll Direction Margin between items in recycler view Android How to add a recyclerView inside another recyclerView RecyclerView - Get view at particular position Recyclerview inside ScrollView not scrolling smoothly

Examples related to expand

RecyclerView expand/collapse items Show/Hide Table Rows using Javascript classes Expand and collapse with angular js Apache POI Excel - how to configure columns to be expanded?