Android学习笔记-使用Scroller来滚动视图
2016-01-17 17:59
447 查看
Scroller滚动视图可以实现平滑移动的效果,而不是瞬间完成的移动,接下里我们实现一个view可随手指移动而移动,当放开手指的时候回到原位置,使用Scroller需要三步,接下来一一介绍
scrollBy与scrollTo都是移动的是ViewGroup的内容,当在view中调用时移动的是View的内容,如TextView移动的为文字
Api的说明Called by a parent to request that a child update its values for mScrollX and mScrollY if necessary. This will typically be done if the child is animating a scroll using a {@link android.widget.Scroller Scroller}object.
当view的父容器想要更新mScrollX,mScrollY时被调用,而mScrollX为当内容被滚到后的x州的偏移距离
2.mScroll.computeScrollOffset()该方法计算mScroll的偏移量,当滑动没有完成的时候返回true,然后通过((View)getParent()).scrollTo(mScroll.getCurrX(),mScroll.getCurrY());来对view进行滑动,真正起作用的还是scrollTo方法,Scroller类只是提供在一段时间内,他的值会改变,在继续调用invaidate方法来反复时ViewGroup中的内容进行移动
scrollBy与scrollTo都是移动的是ViewGroup的内容,当在view中调用时移动的是View的内容,如TextView移动的为文字
1.初始化Scroller
通过他的构造函数来初始化Scroller mScroller = new Scroller(mContext);
2.重写computeScroll方法,显示平滑的移动
看一下如何来重写@Override public void computeScroll() { super.computeScroll(); if(mScroll.computeScrollOffset()){ ((View)getParent()).scrollTo(mScroll.getCurrX(),mScroll.getCurrY()); //通过重绘来不断调用computeScroll方法 invalidate(); } }
Api的说明Called by a parent to request that a child update its values for mScrollX and mScrollY if necessary. This will typically be done if the child is animating a scroll using a {@link android.widget.Scroller Scroller}object.
当view的父容器想要更新mScrollX,mScrollY时被调用,而mScrollX为当内容被滚到后的x州的偏移距离
3.startScroll 开启滚动
当放开手指时,@Override public boolean onTouchEvent(MotionEvent event) { Log.d("xinwa","--onTouchEvent--"); int x = (int) event.getX(); int y = (int) event.getY(); switch (event.getAction()){ case MotionEvent.ACTION_DOWN: lastX = x; lastY = y; break; case MotionEvent.ACTION_MOVE: int offsetX = lastX - x; int offsetY = lastY - y; ((View)getParent()).scrollBy(offsetX, offsetY); invalidate(); break; case MotionEvent.ACTION_UP: ViewGroup viewGroup = (ViewGroup) getParent(); mScroll.startScroll(viewGroup.getScrollX(), viewGroup.getScrollY(), -viewGroup.getScrollX(), -viewGroup.getScrollY()); invalidate(); break; } return true; }
说一下调用的过程
1.首先当我们手指离开的时候,调用了mScroller.startScroll()设置了要进行滚动的偏移量,然后调用invalidate()方法去重绘,在onDraw()方法中又会去调用computScroll()方法2.mScroll.computeScrollOffset()该方法计算mScroll的偏移量,当滑动没有完成的时候返回true,然后通过((View)getParent()).scrollTo(mScroll.getCurrX(),mScroll.getCurrY());来对view进行滑动,真正起作用的还是scrollTo方法,Scroller类只是提供在一段时间内,他的值会改变,在继续调用invaidate方法来反复时ViewGroup中的内容进行移动
相关文章推荐
- 开源框架KImageLoader开发及原理剖析(一)
- Android之CursorAdapter用法
- android Criteria的使用
- Android应用开发笔记(10):制作自…
- Android 文件打开方式
- Android中的Environment.getExtern…
- Android中visibility属性VISIBLE、…
- 无需root,清除清理安卓,android的c…
- Android Afinal使用与总结
- Android调用系统相机和自定义相机…
- android animation解析
- Android Studio 快捷键
- android studio没有浮现函数用法和属性说明?
- Android RecyclerView 的基本使用之GridView
- Android listview优化
- Android 笔记 Intent and Bundle day7
- android NDK :使用预编译第三方库
- Android动画详解:
- android 命令行安装apk
- Android onTouch 多点触控实现图片移动缩放