Java 仅在滚动功能完成后获取项目
我正在使用导航菜单视图,并以编程方式滚动它,然后获取其项的Y位置。 但是获取项目位置的代码在列表(使用布局管理器)开始滚动后立即运行,并且在尚未完成滚动和更改位置时运行。 在“scrollToPositionWithOffset”等待scroll操作结束运行后,如何执行其余代码 这是我的密码:Java 仅在滚动功能完成后获取项目,java,android,view,scroll,Java,Android,View,Scroll,我正在使用导航菜单视图,并以编程方式滚动它,然后获取其项的Y位置。 但是获取项目位置的代码在列表(使用布局管理器)开始滚动后立即运行,并且在尚未完成滚动和更改位置时运行。 在“scrollToPositionWithOffset”等待scroll操作结束运行后,如何执行其余代码 这是我的密码: RecyclerView recyclerView = (RecyclerView) navigationView.getChildAt(0); LinearLayoutManager l
RecyclerView recyclerView = (RecyclerView) navigationView.getChildAt(0);
LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
layoutManager.scrollToPositionWithOffset(4, 0);
//it should wait the line above run completely to can run too
mImage.animate().y(navView.getChildAt(4).getY());
通过研究,我发现:
final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false) {
@Override
public void onLayoutChildren(final Recycler recycler, final State state) {
super.onLayoutChildren(recycler, state);
//TODO if the items are filtered, considered hiding the fast scroller here
final int firstVisibleItemPosition = findFirstVisibleItemPosition();
if (firstVisibleItemPosition != 0) {
// this avoids trying to handle un-needed calls
if (firstVisibleItemPosition == -1)
//not initialized, or no items shown, so hide fast-scroller
mFastScroller.setVisibility(View.GONE);
return;
}
final int lastVisibleItemPosition = findLastVisibleItemPosition();
int itemsShown = lastVisibleItemPosition - firstVisibleItemPosition + 1;
//if all items are shown, hide the fast-scroller
mFastScroller.setVisibility(mAdapter.getItemCount() > itemsShown ? View.VISIBLE : View.GONE);
}
};
这里的好处是,它工作良好,甚至可以处理显示/隐藏的键盘
糟糕的是,它会在不感兴趣的情况下被调用(这意味着它有误报),但它不像滚动事件那样频繁,所以对我来说已经足够好了。您应该使用滚动侦听器,侦听滚动状态变为空闲。。见下文
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
mImage.animate().y(navView.getChildAt(4).getY());
recyclerView.removeOnScrollListener(this);
}
}
}
layoutManager.scrollToPositionWithOffset(4, 0);
谢谢,但在我的例子中,有时所有项目都不显示,因为我不需要转到列表的末尾,但我需要知道滚动是否工作并停止,它不需要在列表的最后,但总是在滚动工作并停止时显示。这似乎不工作=/。激发
scrollToPositionWithOffset
后,永远不会调用该方法。