我的问题有解决方案吗?
我目前正在使用SnapHelper但结果是这样的。
如您所见,滚动视图无法在第一个项目中停止,但滚动时其他项目已经能够居中对焦。如何实现每个项目的中心焦点?
代码:
public class ScrollingSnap1 extends AppCompatActivity {
private ArrayList<String> arraylist = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scrolling_snap1);
arraylist.add("1111111111111111111111111111111111111111");
arraylist.add("2222222222222222222222222");
arraylist.add("3333333333333333333333333333333333333333333333333");
arraylist.add("99999999");
arraylist.add("1010101010101001010101010");
Adapter1 adapter1 = new Adapter1(arraylist);
RecyclerView recyclerview = (RecyclerView)findViewById(R.id.recycler2);
SnapHelper snapHelper = new LinearSnapHelper();
recyclerview.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, true));
recyclerview.setAdapter(adapter1);
snapHelper.attachToRecyclerView(recyclerview);
}
}
答案 0 :(得分:0)
为了使第一个和最后一个项目居中,您需要在RecyclerView的开头和结尾处创建额外的空间。一种简单的方法是使用ItemDecoration,如下所示:
class BoundsOffsetDecoration : ItemDecoration() {
override fun getItemOffsets(outRect: Rect,
view: View,
parent: RecyclerView,
state: RecyclerView.State) {
super.getItemOffsets(outRect, view, parent, state)
val itemPosition = parent.getChildAdapterPosition(view)
// It is crucial to refer to layoutParams.width (view.width is 0 at this time)!
val itemWidth = view.layoutParams.width
val offset = (parent.width - itemWidth) / 2
if (itemPosition == 0) {
outRect.left = offset
} else if (itemPosition == state.itemCount - 1) {
outRect.right = offset
}
}
}