扩展ScrollView onScrollEnded从数据库加载多个条目,但每个End只需要一次

时间:2014-07-16 08:54:14

标签: android scrollview onscrolllistener

我知道为什么我的扩展ScrollViews onScrollChanged在使用onScrollEnd达到结束时被多次调用(因为我通过滚动“多次到达终点”并因此多次调用onScrollEnd)并且因为它从数据库加载多个条目虽然我希望它在第一次到达时加载一次。

在我的ExtendedScrollView类中

protected void onScrollChanged(int x, int y, int oldx, int oldy) {

View view = (View) getChildAt(getChildCount() - 1);
int diff = (view.getBottom()-(getHeight()+getScrollY()+view.getTop()));

if (diff == 0) { 

      if (scrollViewListener != null) {

          scrollViewListener.onScrollEnded(this, x, y, oldx, oldy);

      }

  }

   super.onScrollChanged(x, y, oldx, oldy);
}

public interface ScrollViewListener {

   void onScrollEnded(ExtendedScrollView scrollView, int x, int y, int oldx, int oldy);
}

在我的活动中我有

@Override
    public void onScrollEnded(ExtendedScrollView scrollView, int x, int y, int oldx, int oldy) {

   //Called multiple times because of scroll but needed only once 

  //read 6 Strings (for example) from Database and refresh Tableview with that data (working so I think there is no need for the code)

}

有没有办法停止获得多个“结束”(由滚动引起)。只获取OnScrollEnded一次并从DB加载仅6个字符串(因为多次滚动它被调用),然后在接下来的12个Scroll中读取下一个6,依此类推......

感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

我找到了一种方法,我在StackOverflow找到了几个代码并得到了

ExtendedViewClass

public class ExtendedScrollView extends ScrollView {

private Runnable scrollerTask;
private int initialPosition;

private int newCheck = 100;


public interface OnScrollStoppedListener{
void onScrollStopped();
}

private OnScrollStoppedListener onScrollStoppedListener;

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

scrollerTask = new Runnable() {

    public void run() {

        int newPosition = getScrollY();

        View view = (View) getChildAt(getChildCount() - 1);
        int diff = (view.getBottom()-(getHeight()+getScrollY()+view.getTop()));

        if(initialPosition - newPosition == 0 && diff == 0){//has stopped and reached end

            if(onScrollStoppedListener!=null){

                onScrollStoppedListener.onScrollStopped();
            }
        }
    }
 };
}

public void setOnScrollStoppedListener(ExtendedScrollView.OnScrollStoppedListener listener){
onScrollStoppedListener = listener;
 }

public void startScrollerTask(){

initialPosition = getScrollY();
ExtendedScrollView.this.postDelayed(scrollerTask, newCheck);
  }
}

然后在我的活动中

scrollView = (ExtendedScrollView) findViewById(R.id.ScrView);


scrollView.setOnTouchListener(new OnTouchListener() {

    public boolean onTouch(View v, MotionEvent event) {

        if (event.getAction() == MotionEvent.ACTION_UP) {


            scrollView.startScrollerTask();
        }

        return false;
    }
});
scrollView.setOnScrollStoppedListener(new OnScrollStoppedListener() {

    public void onScrollStopped() {

        //code here

    }
});

这会检查滚动结束是否结束以及Scroll是否停止然后运行OnScrollStopped,因此只运行一次(不是我以前遇到问题的次数)。