【问题标题】:android linear layout : y and height never match (onScrollChanged)android线性布局:y和高度永远不匹配(onScrollChanged)
【发布时间】:2023-03-11 16:24:01
【问题描述】:

我有一个封装在 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 的高度。

为什么? 谢谢。

【问题讨论】:

标签: android scroll


【解决方案1】:

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

This link 可能会有所帮助。

【讨论】:

【解决方案2】:

我用来检测滚动结束的代码。计时器是这样的,因此结束事件在到达结束时不会重复触发。

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

       }
   }
}

【讨论】:

    猜你喜欢
    • 2021-05-03
    • 2015-12-15
    • 2020-05-07
    • 1970-01-01
    • 2020-10-30
    • 2011-11-04
    • 1970-01-01
    • 2020-11-23
    • 1970-01-01
    相关资源
    最近更新 更多