这是我之前提出的问题的跟进。
在我的应用程序中,我正在尝试拥有一个水平
问题在于当
我需要实现一个新的
在我的应用程序中,我正在尝试拥有一个水平
RecyclerView
,它会自动对齐到中心项。为此,我附加了一个LinearSnapHelper
。我还创建了一个项目装饰,将一些左/右填充添加到第一个/最后一个元素中:public class OffsetItemDecoration extends RecyclerView.ItemDecoration {
private Context ctx;
public OffsetItemDecoration(Context ctx){
this.ctx = ctx;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
super.getItemOffsets(outRect, view, parent, state);
int nCols = ActivityUtils.getNumCols(ctx);
int colWidth = (int)(getScreenWidth()/(float)(nCols));
if(parent.getChildAdapterPosition(view) == 0){
int offset = Math.round(getScreenWidth() / 2f - colWidth / 2f);
setupOutRect(outRect, offset, true);
}
else if (parent.getChildAdapterPosition(view) == state.getItemCount()-1){
int offset = Math.round(getScreenWidth() / 2f - colWidth / 2f);
setupOutRect(outRect, offset, false);
}
}
private void setupOutRect(Rect rect, int offset, boolean start){
if(start) rect.left = offset;
else rect.right = offset;
}
private int getScreenWidth(){
WindowManager wm = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
return size.x;
}
}
问题在于当
RecyclerView
第一次填充时,第一项会居中显示并被选中,但是当我尝试水平滚动并返回到第一项时,最左边的可选项是第二项(位置1
)。对于最后一项也是同样的情况,可以对齐到最右边的项是倒数第二项(state.getItemCount() - 2
)。我需要实现一个新的
SnapHelper
还是我做错了什么?