Scroll offset of GridView

被刻印的时光 ゝ 提交于 2019-12-23 10:08:15

问题


Is there a way to determine the current scroll offset or scroll position of a GridView?

View.getScrollY() // Underlying var is not updated during a scroll.

I have tried setting an OnScrollListener but the onScroll callback is not fine grained enough for my purposes.

Here is the how I'm attempting to determine the scroll offset using an OnScrollListener.

private int getScrollY() {
    int top = 0;
    if (mGridView.getChildCount() > 0) {
        final View firstView = mGridView.getChildAt(0);
        top = firstView.getTop();
    }
    return top;
}

The issue with this code is that the returned y offset is inaccurate when scrolling upwards; the top view is recycled and hence, the y offset seems to jump;

Is there a nice way of calculating the scroll offset of a GridView? I can't seem to find a good solution.


回答1:


Use this.

public class CustomGridView extends GridView {

    public CustomGridView(Context context) {
        super(context);
    }

    public CustomGridView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomGridView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    /* ADD THIS */
    @Override
    public int computeVerticalScrollOffset() {
        return super.computeVerticalScrollOffset();
    }
}

Returns an int value when called




回答2:


You can use GridView.getFirstVisiblePosition().

http://developer.android.com/reference/android/widget/AdapterView.html#getFirstVisiblePosition()



来源:https://stackoverflow.com/questions/17453069/scroll-offset-of-gridview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!