Reputation: 11419
I have already used this:
mRecyclerView.getLayoutManager().scrollToPosition(0);
to programmatically scroll a RecyclerView
with a LinearLayoutManager
.
I was trying to do the same with a RecyclerView
with a GridLayoutManager
.
The problem is that scrollToPosition does not really make sense because an item can be in the middle of a line. Anyway I tried that code and it didn't do anything.
Is there a way to programmatically scroll a RecyclerView
with a GridLayoutManager
?
Upvotes: 1
Views: 3207
Reputation: 11419
Actually:
mRecyclerView.getLayoutManager().scrollToPosition(0);
works. In my case it wasn't because I was calling it synchronously in the method:
public void onDestroyActionMode(ActionMode mode)
It was enough to post a runnable (without any delay) to the looper of the main thread.
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
if (mRecyclerView != null) {
mRecyclerView.scrollToPosition(0);
}
}
});
Upvotes: 2
Reputation: 39
You can use method "scrollVerticallyBy" of GridLayoutManager
int scrollVerticallyBy (int dy,
RecyclerView.Recycler recycler,
RecyclerView.State state)
Scroll vertically by dy pixels in screen coordinates and return the distance traveled. The default implementation does nothing and returns 0.
Ref: scrollVerticallyBy
Upvotes: 0