监听HorizontalScrollView滑动到最左/最右

来源:互联网 发布:剑灵人族捏脸数据2016 编辑:程序博客网 时间:2024/06/06 22:17

监听ScrollView滑动停止后,滚动条的位置,是在最左?最右?其它地方?

1,先定制HorizontalScrollView

import android.content.Context;import android.graphics.Rect;import android.util.AttributeSet;import android.widget.HorizontalScrollView;public class ScrollViewCustom extends HorizontalScrollView{private Runnable scrollerTask;private int intitPosition;private int newCheck = 100;private int childWidth = 0;public interface OnScrollStopListner{/** * scroll have stoped */void onScrollStoped();/** * scroll have stoped, and is at left edge */void onScrollToLeftEdge();/** * scroll have stoped, and is at right edge */void onScrollToRightEdge();/** * scroll have stoped, and is at middle */void onScrollToMiddle();}private OnScrollStopListner onScrollstopListner;public ScrollViewCustom(Context context, AttributeSet attrs){super(context, attrs);scrollerTask = new Runnable(){@Overridepublic void run(){int newPosition = getScrollX();if (intitPosition - newPosition == 0){if(onScrollstopListner == null){return;}onScrollstopListner.onScrollStoped();Rect outRect = new Rect();getDrawingRect(outRect);if(getScrollX() == 0){onScrollstopListner.onScrollToLeftEdge();}else if(childWidth + getPaddingLeft() + getPaddingRight() == outRect.right){onScrollstopListner.onScrollToRightEdge();}else{onScrollstopListner.onScrollToMiddle();}} else{intitPosition = getScrollX();postDelayed(scrollerTask, newCheck);}}};}public void setOnScrollStopListner(OnScrollStopListner listner){onScrollstopListner = listner;}public void startScrollerTask(){intitPosition = getScrollX();postDelayed(scrollerTask, newCheck);checkTotalWidth();}private void checkTotalWidth(){if(childWidth > 0){return;}for(int i = 0; i < getChildCount(); i++){childWidth += getChildAt(i).getWidth();}}}

2,使用

    protected void onCreate(Bundle savedInstanceState)    {        final ScrollViewCustom scrollView;        scrollView.setOnTouchListener(new OnTouchListener()        {            public boolean onTouch(View v, MotionEvent event)            {                if (event.getAction() == MotionEvent.ACTION_UP)                {                    scrollView.startScrollerTask();                }                return false;            }        });        scrollView.setOnScrollStopListner(new OnScrollStopListner()        {            public void onScrollToRightEdge()            {            }            public void onScrollToMiddle()            {            }            public void onScrollToLeftEdge()            {            }            public void onScrollStoped()            {            }        });    } 


原创粉丝点击