我使用RecyclerView
水平显示项目。我想将所选项目设置为视图的中心,如此
我就是这样做的:
LinearLayoutManager layoutManager
= new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
recyclerView.setLayoutManager(layoutManager);
答案 0 :(得分:3)
要从RecyclerView获取屏幕上的中间项目,可以将OnScrollListener附加到RecyclerView,在侦听器内部,您应该获取当前项目的位置,然后检查给定项目的区域是否在屏幕中间。
Kotlin中的代码示例:
// Attach OnScrollListener to your RecyclerView
addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
recyclerView.post {
selectMiddleItem()
}
}
})
// implementation of method that is called from OnScrollListener
private fun selectMiddleItem() {
val firstVisibleIndex = layoutManager.findFirstVisibleItemPosition()
val lastVisibleIndex = layoutManager.findLastVisibleItemPosition()
val visibleIndexes = listOf(firstVisibleIndex..lastVisibleIndex).flatten()
for (i in visibleIndexes) {
val vh = findViewHolderForLayoutPosition(i)
if (vh?.itemView == null) {
continue
}
val location = IntArray(2)
vh.itemView.getLocationOnScreen(location)
val x = location[0]
val halfWidth = vh.itemView.width * .5
val rightSide = x + halfWidth
val leftSide = x - halfWidth
val isInMiddle = screenWidth * .5 in leftSide..rightSide
if (isInMiddle) {
// "i" is your middle index and implement selecting it as you want
// optionsAdapter.selectItemAtIndex(i)
return
}
}
}
因此,您应该得到如下内容:
答案 1 :(得分:2)
请尝试这种解决方案:
LinearLayoutManager layoutManager = ((LinearLayoutManager)recyclerView.getLayoutManager());
int totalVisibleItems = layoutManager.findLastVisibleItemPosition() - layoutManager.findFirstVisibleItemPosition()
int centeredItemPosition = totalVisibleItems / 2;
recyclerView.smoothScrollToPosition(position);
recyclerView.setScrollY(centeredItemPosition );
希望这有帮助。
答案 2 :(得分:2)
这是用于在滚动或点击迭代时捕捉中心的项目。
您需要在RecyclerView中添加SnapHelper。方法如下:
final RecyclerView recyclerViewObject = view.findViewById(R.id.recyclerViewObjectId);
final LinearSnapHelper snapHelper = new LinearSnapHelper();
snapHelper.attachToRecyclerView(recyclerViewObject);
recyclerViewObject.setOnFlingListener(snapHelper);
然后你只需要调用此代码
recyclerViewObject.addOnItemTouchListener(
new RecyclerItemClickListener(getContext(), recyclerViewObject ,new RecyclerItemClickListener.OnItemClickListener() {
@Override public void onItemClick(View view, int position) {
recyclerViewObject.smoothScrollToPosition(position);
}
@Override public void onLongItemClick(View view, int position) {
}
})
);
答案 3 :(得分:1)
您可以用最少的代码行实现相同的输出。其中,视图是所选适配器项目的视图,StaticData。SCREEN_WIDTH是设备宽度。
View view = rvCategory.getChildAt(pos);
if (view == null)
return;
int scrollX = (view.getLeft() - (StaticData.SCREEN_WIDTH / 2)) + (view.getWidth() / 2);
rvCategory.smoothScrollBy(scrollX, 0);