我正在创建一个水平 RecyclerView 轮播,并从 RecyclerView 的第一个项目开始缩放焦点项目。
自定义CenterZoomLayoutManager的代码:
public class CenterZoomLayoutManager extends LinearLayoutManager {
private final float mShrinkAmount = 0.15f;
private final float mShrinkDistance = 0.9f;
public CenterZoomLayoutManager(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
}
@Override
public int scrollHorizontallyBy(int dx, RecyclerView.Recycler recycler, RecyclerView.State state) {
int orientation = getOrientation();
if (orientation == HORIZONTAL) {
int scrolled = super.scrollHorizontallyBy(dx, recycler, state);
float midpoint = getWidth() / 2.f;
float d0 = 0.f;
float d1 = mShrinkDistance * midpoint;
float s0 = 1.f;
float s1 = 1.f - mShrinkAmount;
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
float childMidpoint =
(getDecoratedRight(child) + getDecoratedLeft(child)) / 2.f;
float d = Math.min(d1, Math.abs(midpoint - childMidpoint));
float scale = s0 + (s1 - s0) * (d - d0) / (d1 - d0);
child.setScaleX(scale);
child.setScaleY(scale);
}
return scrolled;
} else return 0;
}
@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
super.onLayoutChildren(recycler, state);
scrollHorizontallyBy(0, recycler, state);
}
}
而在我的Fragment
,我有以下内容:
private void onSetRecyclerView() {
recyclerView = fragmentView.findViewById(R.id.recyclerView);
if (recyclerView != null) {
RecyclerView.LayoutManager layoutManager = new CenterZoomLayoutManager(context, LinearLayoutManager.HORIZONTAL,
false);
recyclerView.scrollToPosition(storeList.size() / 2);
final SnapHelper snapHelper = new LinearSnapHelper();
snapHelper.attachToRecyclerView(recyclerView);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
}
}
我想从以下位置启动我的 RecyclerView中心项目而不是从起始位置开始。
Culprit:
in my CenterZoomLayoutManager
,我将像素偏移开始设置为0 pixels通过scrollHorizontallyBy(0, recycler, state)
.
Problem:
我找不到一种方法来传递由以下命令创建的偏移像素recyclerView.scrollToPosition(storeList.size() / 2)
to the CenterZoomLayoutManager
。我尝试寻找不同的内置方法来获取 X 偏移量,但到目前为止还没有成功。