我有一个物品的RecyclerView和一个StaggeredGridLayoutManager类型的layoutManager。我处于一个有趣的情况,我希望我的项目交错看起来像这样:
但我的观点大小相同,所以他们不会错开。要纠正这个问题,我需要在第二列的开头添加一个偏移量。由于我还创建了自己的自定义装饰器类,我认为实现此目的的最佳方法是使用getItemsOffsets方法为列表中的第一个右列项添加偏移量。
以下是我的装饰器类的相关代码:
public class StampListDecoration extends RecyclerView.ItemDecoration {
...
@Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
super.getItemOffsets(outRect, view, parent, state);
// good example here: https://stackoverflow.com/questions/29666598/android-recyclerview-finding-out-first-and-last-view-on-itemdecoration/30404499#30404499
/**
* Special case. Te first right side item in the list should have an extra 50% top
* offset so that these equal sized views are perfectly staggered.
*/
if (parent.getChildAdapterPosition(view) == 1) {
/**
* We would normally do a outRect.top = view.getHeight()/2 to create a 50% top offset on the first right item in the list.
* However, problems would arise if we paused the app when the top right item was scrolled off screen.
* In this situation, when we re-inflated the recyclerview since the view was off screen
* Android would say the height of the view was zero. So instead I added code that
* looked for the height of the top most view that was visible (and would therefore
* have a height.
*
* see https://stackoverflow.com/questions/29463560/findfirstvisibleitempositions-doesnt-work-for-recycleview-android
* because as a staggeredGrid layout you have a special case first visible method
* findFirstVisibleItemPositions that returns an array of (notice the S on the end of
* the method name.
*/
StaggeredGridLayoutManager layoutMngr = ((StaggeredGridLayoutManager) parent.getLayoutManager());
int firstVisibleItemPosition = layoutMngr.findFirstVisibleItemPositions(null)[0];
int topPos = 0;
try {
topPos = parent.getChildAt(firstVisibleItemPosition).getMeasuredHeight()/2;
} catch (Exception e) {
e.printStackTrace();
}
outRect.set(0, topPos, 0, 0);
} else {
outRect.set(0, 0, 0, 0);
}
}
}
我的问题是,当我的活动暂停/恢复时,这些偏移不会保存到状态。因此,当我切换到另一个应用程序并切换回来时,我的RecyclerView中的右列滑回到顶部......我失去了我的错位。
有人可以告诉我如何保存我的偏移状态吗?应该保存偏移的位置在哪里?我假设LayoutManager会保存这些信息,我正在保存LayoutManager状态,但这似乎不起作用。