Recyclerview GridLayoutManager scrollToPositionWithOffset不起作用

时间:2017-04-17 13:20:47

标签: java android android-layout android-recyclerview gridlayoutmanager

您好我正在使用RecyclerView和GridLayoutManager来加载图片,但其scrollToPositionWithOffset()方法无效。

我已经在onSavedInstanceState()中保存了recyclelerview第一个可见项目位置,并且我在onViewStateRestored()中检索了它的值,并且我每次都得到正确的位置但是RecyclerView没有滚动到所需的位置。我正在检查通过旋转我的屏幕,但它没有滚动到所需的位置。

这是我的代码:

  @Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt("position", ((GridLayoutManager) recyclerView.getLayoutManager()).findFirstVisibleItemPosition());
}

@Override
public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
    super.onViewStateRestored(savedInstanceState);
    if (savedInstanceState != null) {
        int state = savedInstanceState.getInt("position");
        ((GridLayoutManager) recyclerView.getLayoutManager()).scrollToPositionWithOffset(state, 20);
    }
}

1 个答案:

答案 0 :(得分:0)

使用smoothScrollToPosition()代替scrollToPositionWithOffset()

试试这个:

@Override
public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
    super.onViewStateRestored(savedInstanceState);
    if (savedInstanceState != null) {
        int state = savedInstanceState.getInt("position");
        recyclerView.smoothScrollToPosition(state);
    }
}