man*_*eak 2 java android android-recyclerview
我有一个回收器视图,用于LinearSnapHelper在用户滚动项目时捕捉项目.现在,我想听一下快照,最好是获取被捕捉的项目的索引.但是,我无法弄清楚是否有办法做到这一点.
起初我以为LinearSnapHelper的findTargetSnapPosition()将返回索引卡(如文档说),但是这是不正确的.它为第一个项随机返回-1或0,当滚动列表时,它会被随机调用.有时,该方法根本没有被调用; 有时,索引不正确,有时它是正确的.似乎尝试使用它找到索引是没用的.
那么:我如何找出回收者视图捕捉到的项目?
我设法让这个工作.我不确定这是否是最好的解决方案,但这就是我所做的:
private int selectedPosition = -1;
private LinearLayoutManager layoutManager;
private RecyclerView recyclerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
...
LinearSnapHelper snapHelper = new LinearSnapHelper() {
@Override
public View findSnapView(RecyclerView.LayoutManager layoutManager) {
View view = super.findSnapView(layoutManager);
if (view != null) {
final int newPosition = layoutManager.getPosition(view);
if (newPosition != selectedPosition && recyclerView.getScrollState() == RecyclerView.SCROLL_STATE_IDLE) {
onViewSnapped(newPosition);
selectedPosition = newPosition;
}
}
return view;
}
};
...
}
private void onViewSnapped(int index) {
// YOUR CODE HERE
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
574 次 |
| 最近记录: |