【问题标题】:Scroll offset of GridViewGridView 的滚动偏移量
【发布时间】:2013-07-03 16:14:44
【问题描述】:

有没有办法确定 GridView 的当前滚动偏移量或滚动位置?

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

我已尝试设置 OnScrollListener,但 onScroll 回调的粒度不足以满足我的目的。

这是我尝试使用 OnScrollListener 确定滚动偏移量的方式。

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

此代码的问题是向上滚动时返回的 y 偏移不准确;顶视图被回收,因此 y 偏移似乎跳跃;

有没有一种很好的方法来计算 GridView 的滚动偏移量?我似乎找不到好的解决方案。

【问题讨论】:

    标签: android gridview scroll scroll-offset


    【解决方案1】:

    使用这个。

    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();
        }
    }
    

    调用时返回 int

    【讨论】:

    • 哦,感谢您回答这个问题!想通之后忘记自己回答了。
    • @mdupls 这似乎给出了正确的 Y 偏移量。但是您使用哪个函数将 Gridview 设置为相同的偏移量?我已经尝试了很多,并且无法获得正确的结果。总是处于不同的位置。我猜,这并不像我想象的那么简单。
    • gridview.smoothScrollToPosition(int index)
    • @mdupls 是啊.. 已经试过了,它不是像素完美的.. 这比它应该更难..
    • GridView 有没有computeVerticalScrollOffset 方法? Android Studio 不提供。
    【解决方案2】:

    【讨论】:

    • "此代码的问题是向上滚动时返回的y偏移不准确;顶视图被回收,因此y偏移似乎跳跃;"
    • 基本上,您不能使用第一个可见单元格的顶部属性来管理滚动。视图被回收的那一刻,你有一个上限等于 cell.getHeight() 的跳转
    • 此解决方案确实有效,但前提是每个单元格都具有相同的高度。
    猜你喜欢
    • 2019-09-24
    • 2015-10-09
    • 2020-08-16
    • 2023-03-22
    • 1970-01-01
    • 2015-10-05
    • 2020-08-16
    • 2018-05-14
    • 2016-03-20
    相关资源
    最近更新 更多