android群英传笔记--第三章--自定义控件五粘性上下滑动scrollview
2016-10-27 23:28
260 查看
这次自定义的是ViewGroup 因此需要在onMeasure onLayout方法中为孩子测量大小 和指定位置。
测量每个孩子
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int count = getChildCount(); for (int i = 0; i < count; ++i) { View childView = getChildAt(i); measureChild(childView, widthMeasureSpec, heightMeasureSpec); } }
为每个孩子指定位置
@Override protected void onLayout(boolean changed, int l, int t, int r, int b) { int childCount = getChildCount(); // 设置ViewGroup的高度 MarginLayoutParams mlp = (MarginLayoutParams) getLayoutParams(); mlp.height = mScreenHeight * childCount; setLayoutParams(mlp); for (int i = 0; i < childCount; i++) { View child = getChildAt(i); if (child.getVisibility() != View.GONE) { child.layout(l, i * mScreenHeight, r, (i + 1) * mScreenHeight); } } }
在onTouchEvent move 中根据scrollBy 移动 回弹动画 由 scrollTo(0, mScroller.getCurrY()) 控制
@Override public void computeScroll() { super.computeScroll(); if (mScroller.computeScrollOffset()) { scrollTo(0, mScroller.getCurrY()); postInvalidate(); } }
最后是最难写的
@Override public boolean onTouchEvent(MotionEvent event) { int y = (int) event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: mLastY = y; mStart = getScrollY(); break; case MotionEvent.ACTION_MOVE: if (!mScroller.isFinished()) { mScroller.abortAnimation(); } int dy = mLastY - y; if (getScrollY() < 0) { dy = 0; } if (getScrollY() > getHeight() - mScreenHeight) { dy = 0; } scrollBy(0, dy); mLastY = y; break; case MotionEvent.ACTION_UP: int dScrollY = checkAlignment(); if (dScrollY > 0) { if (dScrollY < mScreenHeight / 3) { mScroller.startScroll( 0, getScrollY(), 0, -dScrollY); } else { mScroller.startScroll( 0, getScrollY(), 0, mScreenHeight - dScrollY); } } else { if (-dScrollY < mScreenHeight / 3) { mScroller.startScroll( 0, getScrollY(), 0, -dScrollY); } else { mScroller.startScroll( 0, getScrollY(), 0, -mScreenHeight - dScrollY); } } break; } postInvalidate(); return true; }
相关文章推荐
- android群英传笔记--第三章--自定义控件五粘性上下滑动scrollview
- android群英传笔记--第三章--自定义控件五粘性上下滑动scrollview
- android群英传笔记--第三章--自定义控件五粘性上下滑动scrollview
- android群英传笔记--第三章--自定义控件五粘性上下滑动scrollview
- android群英传笔记--第三章--自定义控件五粘性上下滑动scrollview
- android群英传笔记--第三章--自定义控件五粘性上下滑动scrollview
- android群英传笔记--第三章--自定义控件五粘性上下滑动scrollview
- android群英传笔记--第三章--自定义控件五粘性上下滑动scrollview
- android群英传笔记--第三章--自定义控件二topView的简单封装
- android群英传笔记--第三章--自定义控件二topView的简单封装
- android群英传笔记--第三章--自定义控件四音频条形图
- android群英传笔记--第三章--自定义控件三简单形状View
- android群英传笔记--第三章--自定义控件三简单形状View
- android群英传笔记--第三章--自定义控件一跑马灯光扫过字体
- android群英传笔记--第三章--自定义控件三简单形状View
- android群英传笔记--第三章--自定义控件四音频条形图
- android群英传笔记--第三章--自定义控件三简单形状View
- android群英传笔记--第三章--自定义控件二topView的简单封装
- android群英传笔记--第三章--自定义控件三简单形状View
- android群英传笔记--第三章--自定义控件一跑马灯光扫过字体