问题描述
在我的RecyclerView
中,我有一些项目可以让用户滚动并看到,现在我想保存该位置并滚动回来,下面的代码始终返回0,而我无法保存
in my RecyclerView
i have some items that user can scroll and see that, now i want to save this position and scroll that after come back, this below code return 0 always and i cant save that
recyclerMarketLists.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
@Override
public void onScrollChanged() {
recyclerViewCurrentScrolledPosition = recyclerMarketLists.getScrollY();
Log.e("Y: ", recyclerViewCurrentSceolledPosition + "");
}
});
Logcat:
07-07 18:28:30.919 2124-2124/com.sample.presentationproject E/Y:: 0
推荐答案
您正在尝试获取有关错误对象的信息.这不是RecyclerView
也不是Adapter
责任,而是RecyclerView的LayoutManager.
You are trying to get the info on the wrong object. It is not the RecyclerView
nor the Adapter
responsibility but the RecyclerView's LayoutManager.
我建议代替添加RecyclerView.OnScrollListener
并使用onScrollStateChanged(RecyclerView recyclerView, int newState)
回调(为您提供newState
),而不是通用的ViewTreeObserver.OnScrollChangedListener()
,您应该使用SCROLL_STATE_IDLE
来获取其位置.含义:
Instead of the generic ViewTreeObserver.OnScrollChangedListener()
I would recommend to add instead the RecyclerView.OnScrollListener
and use the onScrollStateChanged(RecyclerView recyclerView, int newState)
callback which gives you the newState
, you should use SCROLL_STATE_IDLE
to fetch its position. Meaning:
yourRecyclerView.getLayoutManager().findFirstVisibleItemPosition();
关于所说的回调方法.希望我对您足够清楚,您可以在此处找到有关这些类的文档:
On said callback method. Hope I made this clear enough for your, you can find documentation on the classes here:
这篇关于Android如何在用户滚动到项目的recyclerview上获取当前位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!