android 线性布局:y 和高度永远不匹配 (onScrollChanged)

android linear layout : y and height never match (onScrollChanged)

我有一个封装在 ScrollView 中的 LinearLayout(垂直)。 LinearLayout是动态加载的,我想在滚动到页面底部时加载更多数据。

为了知道何时到达页面底部,我覆盖了 ScrollView.onScrollChanged() 方法:

public class VerticalScrollView extends ScrollView {

    private IVerticalScrollListener listener;
    private LinearLayout list;

    public VerticalScrollView(Context context, AttributeSet attributes) {
        super(context, attributes);
    }

    public void setListener(IVerticalScrollListener listener) {
        this.listener = listener;
    }

    @Override
    protected void onScrollChanged(int x, int y, int oldx, int oldy) {
        super.onScrollChanged(x, y, oldx, oldy);

        if (list == null) {
            list = (LinearLayout) findViewById(R.id.list);
        }

        final int bottom = list.getMeasuredHeight();

        if (y >= bottom) { //never occures
            listener.onPageBottomReached();
        }
    }

}

问题是 "y" 值总是(远)小于 LinearLayout 高度。

为什么? 谢谢。

你不应该通过高度来检测这个。相反,您应该检测当前在用户屏幕上的项目。

This link 可能会有帮助。

我用来检测滚动结束的代码。定时器是为了在到达结束时结束事件不会重复触发。

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.ScrollView;

public class EndDetectableScrollView extends ScrollView {

   private long mLastEndCall = 0;
   private ScrollViewListener scrollViewListener = null;

   public EndDetectableScrollView(Context context) {
      super(context);

   }

   public EndDetectableScrollView(Context context, AttributeSet attrs) {
      super(context, attrs);

   }

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


   public void setScrollViewListener(ScrollViewListener scrollViewListener)
   {
      this.scrollViewListener = scrollViewListener;
   }

   @Override
   protected void onScrollChanged(int l, int t, int oldl, int oldt) {
       super.onScrollChanged(l, t, oldl, oldt);

       if ( scrollViewListener != null) {
        View view = (View) getChildAt(0);
           int diff = (view.getBottom()-(getHeight()+getScrollY()+view.getTop()));
           if ( diff <= 0 ) {  
              long currentTime = System.currentTimeMillis();
              if ( currentTime > mLastEndCall + 1000)
              {
                 Log.d("TAG","CurrentTime: " + currentTime + " lastTime: " + mLastEndCall);
                 mLastEndCall = currentTime;
                 scrollViewListener.onScrollEnd();
              }
           }

       }
   }
}