kingston kingston - 3 months ago 45
Android Question

Programmatically scroll a RecyclerView with GridLayoutManager

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
?

Answer

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);
            }
        }
    });