Scroll to bottom of RecyclerView programmatically
Workaround to scroll RecyclerView to bottom, since RecyclerView.scrollToPosition() didn't work well when the last view item has a bigger layout.
private void scrollToBottom(final RecyclerView recyclerView) {
// scroll to last item to get the view of last item
final LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
final RecyclerView.Adapter adapter = recyclerView.getAdapter();
final int lastItemPosition = adapter.getItemCount() - 1;
layoutManager.scrollToPositionWithOffset(lastItemPosition, 0);
recyclerView.post(new Runnable() {
@Override
public void run() {
// then scroll to specific offset
View target = layoutManager.findViewByPosition(lastItemPosition);
if (target != null) {
int offset = recyclerView.getMeasuredHeight() - target.getMeasuredHeight();
layoutManager.scrollToPositionWithOffset(lastItemPosition, offset);
}
}
});
}