Android如何在用户滚动到项目的recyclerview上获取当前位置 [英] Android how can i get current positon on recyclerview that user scrolled to item

查看:1144
本文介绍了Android如何在用户滚动到项目的recyclerview上获取当前位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的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();

正如里克·范·韦尔岑(Rik van Velzen)所指出的那样,您可能需要投放自己的 LayoutManagerLinearLayoutManagerGridLayoutManager (您必须强制转换为所使用的正确类型)以访问这些 findVisibleXXXX()方法.

As Rik van Velzen pointed out, you probably need to cast your LayoutManager to a LinearLayoutManager or GridLayoutManager (you have to cast to the correct type you are using) to access these findVisibleXXXX() methods.

关于所说的回调方法.希望我对您足够清楚,您可以在此处找到有关这些类的文档:

On said callback method. Hope I made this clear enough for your, you can find documentation on the classes here:

RecyclerView.OnScrollListener

yigit(Google)在可见位置的响应

这篇关于Android如何在用户滚动到项目的recyclerview上获取当前位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆