获取 NestedScrollView 内的第一个可见视图

Igo*_*vić 1 android android-nestedscrollview

我有下一个问题。

我正在尝试在 NestedScrollView 中获取第一个可见项目。实际上,里面的第一个也是唯一的视图是 LinearLayout(因为滚动视图只能容纳一个直接子视图),但我试图在其中获取第一个可见项。我搜索了很多,但没有成功。

通过这种方法,我想避免在另一个 RecyclerView 中使用 RecyclerView。我发现这是一个不好的做法。

PS 我不想使用 ListView 或 RecyclerView

提前致谢

Igo*_*vić 6

好的,我找到了一个解决方案:

        final Rect scrollBounds = new Rect();
        questionAndAnswerScroll.getHitRect(scrollBounds);
        questionAndAnswerScroll.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                for (int i = 0; i < questionAndAnswerHolder.getChildCount(); i++) {
                    View childView = questionAndAnswerHolder.getChildAt(i);
                    if (childView != null) {
                        if (childView.getLocalVisibleRect(scrollBounds)) {
                            //Here is the position of first visible view
                            positionToScroll = i;
                            break;
                        }
                    }
                }
            }
        });
Run Code Online (Sandbox Code Playgroud)