本文为楼主原创,转载请表明出处:http://blog.csdn.net/suma_sun/article/details/52900476
上一篇博文介绍了onTouchEvent()手势控制相关的一些坐标概念,这篇文章结合上一篇内容加上Scroller实现一个简单的带黏性滑动的ScrollView。
思路
- 滑动的时候判断最终偏移量是不是超出了子view(ViewGroup内容)的范围,如果超出了就限制不让其超出,这样就可以做出一个滑动的ScrollView并且不会滑出界
- 当松手(action_up)的时候判断当前偏移量在该子view的什么位置,如果小于三分之一就滑动回该view的头部,如果超出三分之二就滑动到下个view
首先看看我们需要做些什么,自定义View要复写的方法有好几个,我们要复写的有:
1. onMeasure()
2. onLayout()
3. onTouchEvent()
4. computeScroll()
因为是ViewGroup需要计算、定位子View所以需要复写1和2两个函数。
3不用说了,要实现滑动功能必须要实现的函数。
4这是配合Scroller使用的一个函数。
首先介绍下Scroller这个类,这个类是一个工具,并不是实际UI操作。这个工具提供的功能是提供差值计算,就像属性动画一样,要做一个平滑过渡的动画需要用到差值器来辅助提供偏移差值。
下面是一个不使用Scroller的Demo。
差别很明显。
onMeasure
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//遍历子View,测量子View
int count = getChildCount();
for (int i = 0; i < count; i++) {
View view = getChildAt(i);
measureChild(view, widthMeasureSpec, heightMeasureSpec);
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
onMeasure()没什么好说的,遍历子view,测量子view。
onLayout
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
// 这里的四个坐标都是以ViewGroup来参照的,而不是屏幕的原点
// top默认0
// left默认0
// right默认屏幕宽度,ViewGroup的布局mactch_parent
// bottom默认屏幕高度,ViewGroup的布局mactch_parent
int count = getChildCount();
for (int i = 0; i < count; i++) {
View view = getChildAt(i);
//这个demo模仿垂直的ScrollView所以就没有累计宽度
int right = view.getMeasuredWidth();
//设置子View摆放位置
//mMaxHeight初始化为0
view.layout(l , mMaxHeight, right, mMaxHeight + view.getMeasuredHeight());
mMaxHeight += view.getMeasuredHeight();
//mHeights是一个集合,用于保存每个自view的高度,用于粘性滑动判断
mHeights.add(mMaxHeight);
if(right > mMaxWidth){
mMaxWidth = right;
}
}
}
要说明的都已经在注释上了。