I am using recylerview in my application and whenever new element is added to recyclerview, it scrolls to last element by using
recyclerView.scrollToPosition
recyclerView.smoothScrollToPosition(recyclerView.getAdapter().getItemCount());
layoutManager.scrollToPositionWithOffset(chatMessageAdapter.getItemCount() - 1, 0);
Although this an old question, I experienced this problem today and I found out that none of of the above method works. This is my solution
recyclerView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v,
int left, int top, int right, int bottom,
int oldLeft, int oldTop, int oldRight, int oldBottom) {
if (bottom < oldBottom) {
final int lastAdapterItem = mAdapter.getItemCount() - 1;
recyclerView.post(new Runnable() {
@Override
public void run() {
int recyclerViewPositionOffset = -1000000;
View bottomView = linearLayoutManager.findViewByPosition(lastAdapterItem);
if (bottomView != null) {
recyclerViewPositionOffset = 0 - bottomView.getHeight();
}
linearLayoutManager.scrollToPositionWithOffset(lastAdapterItem, recyclerViewPositionOffset);
}
});
}
});
}
It works for me
LinearLayoutManager layoutManager = new LinearLayoutManager(context);
layoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(layoutManager);
Add this your activity or fragment:
if (Build.VERSION.SDK_INT >= 11) {
recyclerView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v,
int left, int top, int right, int bottom,
int oldLeft, int oldTop, int oldRight, int oldBottom) {
if (bottom < oldBottom) {
recyclerView.postDelayed(new Runnable() {
@Override
public void run() {
recyclerView.smoothScrollToPosition(
recyclerView.getAdapter().getItemCount() - 1);
}
}, 100);
}
}
});
}
It works properly in support library version 27.0.1
There is nothing to set in the manifest.
val currentScrollPosition = 0
recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
currentScrollPosition = recyclerView.computeVerticalScrollOffset() + recyclerView.computeVerticalScrollExtent()
}
override fun onScrollStateChanged(recyclerView: RecyclerView?, newState: Int) { }
})
storyList.addOnLayoutChangeListener { view, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom ->
if (bottom < oldBottom) {
if (currentScrollPosition >= recyclerView.computeVerticalScrollRange()) {
recyclerVIew.post {
recyclerView.overScrollMode = RecyclerView.OVER_SCROLL_NEVER
recyclerView.smoothScrollBy(0, recyclerView.computeVerticalScrollRange() - recyclerView.computeVerticalScrollOffset() + recyclerView.computeVerticalScrollExtent())
}
}
} else {
recyclerView.overScrollMode = RecyclerView.OVER_SCROLL_ALWAYS
}
}