Android “我该怎么做?”;“拯救国家”;我的Recyclerview项目装饰&;补偿?
我有一个项目的RecyclerView和一个layoutManager类型的layoutManager。我当时的处境很有趣,我希望我的物品交错排列,如下所示: 但我的观点都是相同的,所以它们不会错开。为了纠正这个问题,我需要在第二列的开头添加一个偏移量。因为我也在创建自己的自定义装饰器类,所以我认为实现这一点的最佳方法是使用getItemsOffsets方法为列表中的第一个右列项添加一个偏移量 以下是我的decorator类的相关代码:Android “我该怎么做?”;“拯救国家”;我的Recyclerview项目装饰&;补偿?,android,android-recyclerview,Android,Android Recyclerview,我有一个项目的RecyclerView和一个layoutManager类型的layoutManager。我当时的处境很有趣,我希望我的物品交错排列,如下所示: 但我的观点都是相同的,所以它们不会错开。为了纠正这个问题,我需要在第二列的开头添加一个偏移量。因为我也在创建自己的自定义装饰器类,所以我认为实现这一点的最佳方法是使用getItemsOffsets方法为列表中的第一个右列项添加一个偏移量 以下是我的decorator类的相关代码: public class StampListDecor
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状态,但这似乎不起作用。遇到类似情况时,您是否想出过解决方案?