2016-05-17 52 views

回答

0

如果你使用linearlayoutManager,您可以使用此代码,

linearLayoutManager.scrollToPositionWithOffset(2, 20); 

(linearLayoutManager.void scrollToPositionWithOffset (int position, 
      int offset)) 

偏移设定为0应与顶部

2

第一招滚动到你的项目一致,但每当recyclerView春联它只是将物品放入可见区域,但不能确定物品是否位于中间位置,因此我们找到中间物品,然后检查我们是否位于物品中间或物品的后面,这里是工作逻辑

recyclerView.smoothScrollToPosition(index); 
int firstVisibleItemPosition = rvLayoutManager.findFirstVisibleItemPosition(); 
int lastVisibleItemPosition = rvLayoutManager.findLastVisibleItemPosition(); 

int centerPosition = (firstVisibleItemPosition + lastVisibleItemPosition)/2; 

    if (index > centerPosition) { 
     recyclerView.smoothScrollToPosition(index + 1); 
    } else if (index < centerPosition) { 
     recyclerView.smoothScrollToPosition(index - 1); 
    } 
+0

帮我,谢谢 – mohnage7

+0

最欢迎@ mohnage7 –

+0

在水平recyclerView与图片,该解决方案ISN的情况下,不完美。当点击的项目不在中心附近时,它无法居中。 @ Ispam的解决方案https://stackoverflow.com/a/44854796/860311虽然工作完美 –

1

如果您使用的是RecyclerViewLinearLayoutManager这将工作:

private void scrollToCenter(View v) { 
    int itemToScroll = mRecyclerView.getChildPosition(v); 
    int centerOfScreen = mRecyclerView.getWidth()/2 - v.getWidth()/2; 
    mLayoutManager.scrollToPositionWithOffset(itemToScroll, centerOfScreen); 
} 
+0

请尽量避免只是倾销代码作为答案,并尝试解释它的作用和原因。对于那些没有相关编码经验的人来说,你的代码可能并不明显。请修改您的答案,以包含[澄清,上下文,并尝试在答案中提及任何限制,假设或简化。](https://stackoverflow.com/help/how-to-answer) –