alpartis alpartis - 1 month ago 9
Android Question

RecyclerView does not auto scroll to expanded ViewHolder item

I have a RecyclerView containing my list of ViewHolder items. When a user touches an item, its layout/view expands to show more details. Pretty standard stuff and works great ... except in this one situation:

If the user scrolls to the last item in the list, then touches it, that item expands in place and out of view. In other words, as the item expands, it extends the bottom of the list, but the list does not auto scroll to keep all of the expanded item "on screen" or "in view" within the bounds of the RecyclerView.

I have tried to RecyclerView.scrollToPosition() to the last position in the list, but the list doesn't move.

The user can manually scroll the list and bring the full expanded item into view, but I want it to happen automatically.

Thoughts?

Edit: I don't know if this is influencing things, or not, but the list is already manually scrolled to the bottom of the list so it seems like it would be redundant to programmaticaly scroll to the same position. Essentially what I'm trying to do is 'refresh' the scroll position in the list to bring the entire final list entry into view.

Answer Source

I was almost there with the use of the LinearLayoutManager scroll method. The solution, for me, was to use LinearLayoutManager.scrollToPositionWithOffset() while providing the extra size of the expanded view as the offset.

int distanceInPixels;
View firstVisibleChild = recyclerView.getChildAt(0);
int itemHeight = firstVisibleChild.getHeight();
int currentPosition = recyclerView.getChildAdapterPosition(firstVisibleChild);
int p = Math.abs(position - currentPosition);
if (p > 5) distanceInPixels = (p - (p - 5)) * itemHeight;
else       distanceInPixels = p * itemHeight;
layoutMgr.scrollToPositionWithOffset(position, distanceInPixels);