您的位置:首页 > 移动开发 > Android开发

Android应用开发中自定义ViewGroup的究极攻略

2016-05-20 14:58 1361 查看

支持margin,gravity以及水平,垂直排列
最近在学习android的view部分,于是动手实现了一个类似ViewPager的可上下或者左右拖动的ViewGroup,中间遇到了一些问题(例如touchEvent在onInterceptTouchEvent和onTouchEvent之间的传递流程),现在将我的实现过程记录下来。

首先,要实现一个ViewGroup,必须至少重写onLayout()方法(当然还有构造方法啦:))。onLayout()主要是用来安排子View在我们这个ViewGroup中的摆放位置的。除了onLayout()方法之外往往还需要重写onMeasure()方法,用于测算我们所需要占用的空间。

首先,我们来重写onMeasure()方法:(先只考虑水平方向)

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// 计算所有child view 要占用的空间
desireWidth = 0;
desireHeight = 0;
int count = getChildCount();
for (int i = 0; i < count; ++i) {
View v = getChildAt(i);
if (v.getVisibility() != View.GONE) {
measureChild(v, widthMeasureSpec,
heightMeasureSpec);
desireWidth += v.getMeasuredWidth();
desireHeight = Math
.max(desireHeight, v.getMeasuredHeight());
}
}
// count with padding
desireWidth += getPaddingLeft() + getPaddingRight();
desireHeight += getPaddingTop() + getPaddingBottom();
// see if the size is big enough
desireWidth = Math.max(desireWidth, getSuggestedMinimumWidth());
desireHeight = Math.max(desireHeight, getSuggestedMinimumHeight());
setMeasuredDimension(resolveSize(desireWidth, widthMeasureSpec),
resolveSize(desireHeight, heightMeasureSpec));
}


我们计算出所有Visilibity不是Gone的View的宽度的总和作为viewgroup的最大宽度,以及这些view中的最高的一个作为viewgroup的高度。这里需要注意的是要考虑咱们viewgroup自己的padding。(目前先忽略子View的margin)。
onLayout():

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
final int parentLeft = getPaddingLeft();
final int parentRight = r - l - getPaddingRight();
final int parentTop = getPaddingTop();
final int parentBottom = b - t - getPaddingBottom();
if (BuildConfig.DEBUG)
Log.d("onlayout", "parentleft: " + parentLeft + " parenttop: "
+ parentTop + " parentright: " + parentRight
+ " parentbottom: " + parentBottom);
int left = parentLeft;
int top = parentTop;
int count = getChildCount();
for (int i = 0; i < count; ++i) {
View v = getChildAt(i);
if (v.getVisibility() != View.GONE) {
final int childWidth = v.getMeasuredWidth();
final int childHeight = v.getMeasuredHeight();
v.layout(left, top, left + childWidth, top + childHeight);
left += childWidth;
}
}
}


上面的layout方法写的比较简单,就是简单的计算出每个子View的left值,然后调用view的layout方法即可。
现在我们加上xml布局文件,来看一下效果:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<com.example.testslidelistview.SlideGroup
android:id="@+id/sl"
android:layout_width="match_parent"
android:layout_height="500dp"
android:layout_marginTop="50dp"
android:background="#FFFF00" >
<ImageView
android:id="@+id/iv1"
android:layout_width="150dp"
android:layout_height="300dp"
android:scaleType="fitXY"
android:src="@drawable/lead_page_1" />
<ImageView
android:layout_width="150dp"
android:layout_height="300dp"
android:scaleType="fitXY"
android:src="@drawable/lead_page_2" />
<ImageView
android:layout_width="150dp"
android:layout_height="300dp"
android:scaleType="fitXY"
android:src="@drawable/lead_page_3" />
</com.example.testslidelistview.SlideGroup>
</LinearLayout>


效果图如下:

从效果图中我们看到,3个小图连在一起(因为现在不支持margin),然后我们也没办法让他们垂直居中(因为现在还不支持gravity)。

现在我们首先为咱们的ViewGroup增加一个支持margin和gravity的LayoutParams。

@Override
protected android.view.ViewGroup.LayoutParams generateDefaultLayoutParams() {
return new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
}
@Override
public android.view.ViewGroup.LayoutParams generateLayoutParams(
AttributeSet attrs) {
return new LayoutParams(getContext(), attrs);
}
@Override
protected android.view.ViewGroup.LayoutParams generateLayoutParams(
android.view.ViewGroup.LayoutParams p) {
return new LayoutParams(p);
}
public static class LayoutParams extends MarginLayoutParams {
public int gravity = -1;
public LayoutParams(Context c, AttributeSet attrs) {
super(c, attrs);
TypedArray ta = c.obtainStyledAttributes(attrs,
R.styleable.SlideGroup);
gravity = ta.getInt(R.styleable.SlideGroup_layout_gravity, -1);
ta.recycle();
}
public LayoutParams(int width, int height) {
this(width, height, -1);
}
public LayoutParams(int width, int height, int gravity) {
super(width, height);
this.gravity = gravity;
}
public LayoutParams(android.view.ViewGroup.LayoutParams source) {
super(source);
}
public LayoutParams(MarginLayoutParams source) {
super(source);
}
}


xml的自定义属性如下:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<attr name="layout_gravity">
<!-- Push object to the top of its container, not changing its size. -->
<flag name="top" value="0x30" />
<!-- Push object to the bottom of its container, not changing its size. -->
<flag name="bottom" value="0x50" />
<!-- Push object to the left of its container, not changing its size. -->
<flag name="left" value="0x03" />
<!-- Push object to the right of its container, not changing its size. -->
<flag name="right" value="0x05" />
<!-- Place object in the vertical center of its container, not changing its size. -->
<flag name="center_vertical" value="0x10" />
<!-- Place object in the horizontal center of its container, not changing its size. -->
<flag name="center_horizontal" value="0x01" />
</attr>
<declare-styleable name="SlideGroup">
<attr name="layout_gravity" />
</declare-styleable>
</resources>


现在基本的准备工作差不多了,然后需要修改一下onMeasure()和onLayout()。
onMeasure():(上一个版本,我们在计算最大宽度和高度时忽略了margin)

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// 计算所有child view 要占用的空间
desireWidth = 0;
desireHeight = 0;
int count = getChildCount();
for (int i = 0; i < count; ++i) {
View v = getChildAt(i);
if (v.getVisibility() != View.GONE) {
LayoutParams lp = (LayoutParams) v.getLayoutParams();
//将measureChild改为measureChildWithMargin
measureChildWithMargins(v, widthMeasureSpec, 0,
heightMeasureSpec, 0);
//这里在计算宽度时加上margin
desireWidth += v.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
desireHeight = Math
.max(desireHeight, v.getMeasuredHeight() + lp.topMargin + lp.bottomMargin);
}
}
// count with padding
desireWidth += getPaddingLeft() + getPaddingRight();
desireHeight += getPaddingTop() + getPaddingBottom();
// see if the size is big enough
desireWidth = Math.max(desireWidth, getSuggestedMinimumWidth());
desireHeight = Math.max(desireHeight, getSuggestedMinimumHeight());
setMeasuredDimension(resolveSize(desireWidth, widthMeasureSpec),
resolveSize(desireHeight, heightMeasureSpec));
}


onLayout()(加上margin和gravity)

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
final int parentLeft = getPaddingLeft();
final int parentRight = r - l - getPaddingRight();
final int parentTop = getPaddingTop();
final int parentBottom = b - t - getPaddingBottom();
if (BuildConfig.DEBUG)
Log.d("onlayout", "parentleft: " + parentLeft + " parenttop: "
+ parentTop + " parentright: " + parentRight
+ " parentbottom: " + parentBottom);
int left = parentLeft;
int top = parentTop;
int count = getChildCount();
for (int i = 0; i < count; ++i) {
View v = getChildAt(i);
if (v.getVisibility() != View.GONE) {
LayoutParams lp = (LayoutParams) v.getLayoutParams();
final int childWidth = v.getMeasuredWidth();
final int childHeight = v.getMeasuredHeight();
final int gravity = lp.gravity;
final int horizontalGravity = gravity
& Gravity.HORIZONTAL_GRAVITY_MASK;
final int verticalGravity = gravity
& Gravity.VERTICAL_GRAVITY_MASK;
left += lp.leftMargin;
top = parentTop + lp.topMargin;
if (gravity != -1) {
switch (verticalGravity) {
case Gravity.TOP:
break;
case Gravity.CENTER_VERTICAL:
top = parentTop
+ (parentBottom - parentTop - childHeight)
/ 2 + lp.topMargin - lp.bottomMargin;
break;
case Gravity.BOTTOM:
top = parentBottom - childHeight - lp.bottomMargin;
break;
}
}
if (BuildConfig.DEBUG) {
Log.d("onlayout", "child[width: " + childWidth
+ ", height: " + childHeight + "]");
Log.d("onlayout", "child[left: " + left + ", top: "
+ top + ", right: " + (left + childWidth)
+ ", bottom: " + (top + childHeight));
}
v.layout(left, top, left + childWidth, top + childHeight);
left += childWidth + lp.rightMargin;
}
}
}


现在修改一下xml布局文件,加上例如xmlns:ly="http://schemas.android.com/apk/res-auto",的xml命名空间,来引用我们设置的layout_gravity属性。(这里的“res-auto”其实还可以使用res/com/example/testslidelistview来代替,但是前一种方法相对简单,尤其是当你将某个ui组件作为library来使用的时候)
现在的效果图如下:有了margin,有了gravity。

其实在这个基础上,我们可以很容易的添加一个方向属性,使得它可以通过设置一个xml属性或者一个java api调用来实现垂直排列。

下面我们增加一个用于表示方向的枚举类型:

public static enum Orientation {
HORIZONTAL(0), VERTICAL(1);
private int value;
private Orientation(int i) {
value = i;
}
public int value() {
return value;
}
public static Orientation valueOf(int i) {
switch (i) {
case 0:
return HORIZONTAL;
case 1:
return VERTICAL;
default:
throw new RuntimeException("[0->HORIZONTAL, 1->VERTICAL]");
}
}
}


然后我们需要改变onMeasure(),来正确的根据方向计算需要的最大宽度和高度。

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// 计算所有child view 要占用的空间
desireWidth = 0;
desireHeight = 0;
int count = getChildCount();
for (int i = 0; i < count; ++i) {
View v = getChildAt(i);
if (v.getVisibility() != View.GONE) {
LayoutParams lp = (LayoutParams) v.getLayoutParams();
measureChildWithMargins(v, widthMeasureSpec, 0,
heightMeasureSpec, 0);
//只是在这里增加了垂直或者水平方向的判断
if (orientation == Orientation.HORIZONTAL) {
desireWidth += v.getMeasuredWidth() + lp.leftMargin
+ lp.rightMargin;
desireHeight = Math.max(desireHeight, v.getMeasuredHeight()
+ lp.topMargin + lp.bottomMargin);
} else {
desireWidth = Math.max(desireWidth, v.getMeasuredWidth()
+ lp.leftMargin + lp.rightMargin);
desireHeight += v.getMeasuredHeight() + lp.topMargin
+ lp.bottomMargin;
}
}
}
// count with padding
desireWidth += getPaddingLeft() + getPaddingRight();
desireHeight += getPaddingTop() + getPaddingBottom();
// see if the size is big enough
desireWidth = Math.max(desireWidth, getSuggestedMinimumWidth());
desireHeight = Math.max(desireHeight, getSuggestedMinimumHeight());
setMeasuredDimension(resolveSize(desireWidth, widthMeasureSpec),
resolveSize(desireHeight, heightMeasureSpec));
}


onLayout():

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
final int parentLeft = getPaddingLeft();
final int parentRight = r - l - getPaddingRight();
final int parentTop = getPaddingTop();
final int parentBottom = b - t - getPaddingBottom();
if (BuildConfig.DEBUG)
Log.d("onlayout", "parentleft: " + parentLeft + " parenttop: "
+ parentTop + " parentright: " + parentRight
+ " parentbottom: " + parentBottom);
int left = parentLeft;
int top = parentTop;
int count = getChildCount();
for (int i = 0; i < count; ++i) {
View v = getChildAt(i);
if (v.getVisibility() != View.GONE) {
LayoutParams lp = (LayoutParams) v.getLayoutParams();
final int childWidth = v.getMeasuredWidth();
final int childHeight = v.getMeasuredHeight();
final int gravity = lp.gravity;
final int horizontalGravity = gravity
& Gravity.HORIZONTAL_GRAVITY_MASK;
final int verticalGravity = gravity
& Gravity.VERTICAL_GRAVITY_MASK;
if (orientation == Orientation.HORIZONTAL) {
// layout horizontally, and only consider vertical gravity
left += lp.leftMargin;
top = parentTop + lp.topMargin;
if (gravity != -1) {
switch (verticalGravity) {
case Gravity.TOP:
break;
case Gravity.CENTER_VERTICAL:
top = parentTop
+ (parentBottom - parentTop - childHeight)
/ 2 + lp.topMargin - lp.bottomMargin;
break;
case Gravity.BOTTOM:
top = parentBottom - childHeight - lp.bottomMargin;
break;
}
}
if (BuildConfig.DEBUG) {
Log.d("onlayout", "child[width: " + childWidth
+ ", height: " + childHeight + "]");
Log.d("onlayout", "child[left: " + left + ", top: "
+ top + ", right: " + (left + childWidth)
+ ", bottom: " + (top + childHeight));
}
v.layout(left, top, left + childWidth, top + childHeight);
left += childWidth + lp.rightMargin;
} else {
// layout vertical, and only consider horizontal gravity
left = parentLeft;
top += lp.topMargin;
switch (horizontalGravity) {
case Gravity.LEFT:
break;
case Gravity.CENTER_HORIZONTAL:
left = parentLeft
+ (parentRight - parentLeft - childWidth) / 2
+ lp.leftMargin - lp.rightMargin;
break;
case Gravity.RIGHT:
left = parentRight - childWidth - lp.rightMargin;
break;
}
v.layout(left, top, left + childWidth, top + childHeight);
top += childHeight + lp.bottomMargin;
}
}
}
}


现在我们可以增加一个xml属性:

<attr name="orientation">
<enum name="horizontal" value="0" />
<enum name="vertical" value="1" />
</attr>


现在就可以在布局文件中加入ly:orientation="vertical"来实现垂直排列了(ly是自定义的xml命名空间)
布局文件如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<com.example.testslidelistview.SlideGroup
xmlns:gs="http://schemas.android.com/apk/res-auto"
android:id="@+id/sl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="50dp"
android:background="#FFFF00" >
<ImageView
android:id="@+id/iv1"
android:layout_width="300dp"
android:layout_height="200dp"
android:layout_marginBottom="20dp"
gs:layout_gravity="left"
android:scaleType="fitXY"
android:src="@drawable/lead_page_1" />
<ImageView
android:layout_width="300dp"
android:layout_height="200dp"
android:layout_marginBottom="20dp"
gs:layout_gravity="center_horizontal"
android:scaleType="fitXY"
android:src="@drawable/lead_page_2" />
<ImageView
android:layout_width="300dp"
android:layout_height="200dp"
android:layout_marginBottom="20dp"
gs:layout_gravity="right"
android:scaleType="fitXY"
android:src="@drawable/lead_page_3" />
</com.example.testslidelistview.SlideGroup>
</LinearLayout>


现在效果图如下:

重写onTouchEvent()以支持滑动:

要使View滑动,我们可以通过调用scrollTo()和scrollBy()来实现,这里需要注意的是:要使页面向左移动,需要增加mScrollX(就是向scrollBy传递一个正数),同样的,要使页面向上移动,需要增加mScrollY。

@Override
public boolean onTouchEvent(MotionEvent event) {
final int action = event.getAction();
if (BuildConfig.DEBUG)
Log.d("onTouchEvent", "action: " + action);
switch (action) {
case MotionEvent.ACTION_DOWN:
x = event.getX();
y = event.getY();
break;
case MotionEvent.ACTION_MOVE:
float mx = event.getX();
float my = event.getY();
//此处的moveBy是根据水平或是垂直排放的方向,
//来选择是水平移动还是垂直移动
moveBy((int) (x - mx), (int) (y - my));
x = mx;
y = my;
break;
}
return true;
}
//此处的moveBy是根据水平或是垂直排放的方向,
//来选择是水平移动还是垂直移动
public void moveBy(int deltaX, int deltaY) {
if (BuildConfig.DEBUG)
Log.d("moveBy", "deltaX: " + deltaX + " deltaY: " + deltaY);
if (orientation == Orientation.HORIZONTAL) {
if (Math.abs(deltaX) >= Math.abs(deltaY))
scrollBy(deltaX, 0);
} else {
if (Math.abs(deltaY) >= Math.abs(deltaX))
scrollBy(0, deltaY);
}
}



好,现在我们再运行这段代码,就会发现View已经可以跟随手指移动了,但现在的问题是当手指离开屏幕后,View就立即停止滑动了,这样的体验就相当不友好,那么我们希望手指离开后,View能够以一定的阻尼满满地减速滑动。

借助Scroller,并且处理ACTION_UP事件

Scroller是一个用于计算位置的工具类,它负责计算下一个位置的坐标(根据时长,最小以最大移动距离,以及阻尼算法(可以使用自定义的Interpolator))。

Scroller有两种模式:scroll和fling。


scroll用于已知目标位置的情况(例如:Viewpager中向左滑动,就是要展示右边的一页,那么我们就可以准确计算出滑动的目标位置,此时就可以使用Scroller.startScroll()方法)
fling用于不能准确得知目标位置的情况(例如:ListView,每一次的滑动,我们事先都不知道滑动距离,而是根据手指抬起是的速度来判断是滑远一点还是近一点,这时就可以使用Scroller.fling()方法)
现在我们改一下上面的onTouchEvent()方法,增加对ACTION_UP事件的处理,以及初速度的计算。

@Override
public boolean onTouchEvent(MotionEvent event) {
final int action = event.getAction();
if (BuildConfig.DEBUG)
Log.d("onTouchEvent", "action: " + action);
//将事件加入到VelocityTracker中,用于计算手指抬起时的初速度
if (velocityTracker == null) {
velocityTracker = VelocityTracker.obtain();
}
velocityTracker.addMovement(event);
switch (action) {
case MotionEvent.ACTION_DOWN:
x = event.getX();
y = event.getY();
if (!mScroller.isFinished())
mScroller.abortAnimation();
break;
case MotionEvent.ACTION_MOVE:
float mx = event.getX();
float my = event.getY();
moveBy((int) (x - mx), (int) (y - my));
x = mx;
y = my;
break;
case MotionEvent.ACTION_UP:
//maxFlingVelocity是通过ViewConfiguration来获取的初速度的上限
//这个值可能会因为屏幕的不同而不同
velocityTracker.computeCurrentVelocity(1000, maxFlingVelocity);
float velocityX = velocityTracker.getXVelocity();
float velocityY = velocityTracker.getYVelocity();
//用来处理实际的移动
completeMove(-velocityX, -velocityY);
if (velocityTracker != null) {
velocityTracker.recycle();
velocityTracker = null;
}
break;
return true;
}


我们在computeMove()中调用Scroller的fling()方法,顺便考虑一下滑动方向问题

private void completeMove(float velocityX, float velocityY) {
if (orientation == Orientation.HORIZONTAL) {
int mScrollX = getScrollX();
int maxX = desireWidth - getWidth();// - Math.abs(mScrollX);
if (Math.abs(velocityX) >= minFlingVelocity && maxX > 0) {
mScroller.fling(mScrollX, 0, (int) velocityX, 0, 0, maxX, 0, 0);
invalidate();
}
} else {
int mScrollY = getScrollY();
int maxY = desireHeight - getHeight();// - Math.abs(mScrollY);
if (Math.abs(velocityY) >= minFlingVelocity && maxY > 0) {
mScroller.fling(0, mScrollY, 0, (int) velocityY, 0, 0, 0, maxY);
invalidate();
}
}
}


好了,现在我们再运行一遍,问题又来了,手指抬起后,页面立刻又停了下来,并没有实现慢慢减速的滑动效果。

其实原因就是上面所说的,Scroller只是帮助我们计算位置的,并不处理View的滑动。我们要想实现连续的滑动效果,那就要在View绘制完成后,再通过Scroller获得新位置,然后再重绘,如此反复,直至停止。

重写computeScroll(),实现View的连续绘制

@Override
public void computeScroll() {
if (mScroller.computeScrollOffset()) {
if (orientation == Orientation.HORIZONTAL) {
scrollTo(mScroller.getCurrX(), 0);
postInvalidate();
} else {
scrollTo(0, mScroller.getCurrY());
postInvalidate();
}
}
}


computeScroll()是在ViewGroup的drawChild()中调用的,上面的代码中,我们通过调用computeScrollOffset()来判断滑动是否已停止,如果没有,那么我们可以通过getCurrX()和getCurrY()来获得新位置,然后通过调用scrollTo()来实现滑动,这里需要注意的是postInvalidate()的调用,它会将重绘的这个Event加入UI线程的消息队列,等scrollTo()执行完成后,就会处理这个事件,然后再次调用ViewGroup的draw()-->drawChild()-->computeScroll()-->scrollTo()如此就实现了连续绘制的效果。

现在我们再重新运行一下app,终于可以持续滑动了:),不过,当我们缓慢地拖动View,慢慢抬起手指,我们会发现通过这样的方式,可以使得所有的子View滑到屏幕之外,(所有的子View都消失了:()。

问题主要是出在completeMove()中,我们只是判断了初始速度是否大于最小阈值,如果小于这个最小阈值的话就什么都不做,缺少了边界的判断,因此修改computeMove()如下:

private void completeMove(float velocityX, float velocityY) {
if (orientation == Orientation.HORIZONTAL) {
int mScrollX = getScrollX();
int maxX = desireWidth - getWidth();
if (mScrollX > maxX) {
// 超出了右边界,弹回
mScroller.startScroll(mScrollX, 0, maxX - mScrollX, 0);
invalidate();
} else if (mScrollX < 0) {
// 超出了左边界,弹回
mScroller.startScroll(mScrollX, 0, -mScrollX, 0);
invalidate();
} else if (Math.abs(velocityX) >= minFlingVelocity && maxX > 0) {
mScroller.fling(mScrollX, 0, (int) velocityX, 0, 0, maxX, 0, 0);
invalidate();
}
} else {
int mScrollY = getScrollY();
int maxY = desireHeight - getHeight();
if (mScrollY > maxY) {
// 超出了下边界,弹回
mScroller.startScroll(0, mScrollY, 0, maxY - mScrollY);
invalidate();
} else if (mScrollY < 0) {
// 超出了上边界,弹回
mScroller.startScroll(0, mScrollY, 0, -mScrollY);
invalidate();
} else if (Math.abs(velocityY) >= minFlingVelocity && maxY > 0) {
mScroller.fling(0, mScrollY, 0, (int) velocityY, 0, 0, 0, maxY);
invalidate();
}
}
}

ok,现在当我们滑出边界,松手后,会自动弹回。

处理ACTION_POINTER_UP事件,解决多指交替滑动跳动的问题

现在ViewGroup可以灵活的滑动了,但是当我们使用多个指头交替滑动时,就会产生跳动的现象。原因是这样的:

我们实现onTouchEvent()的时候,是通过event.getX(),以及event.getY()来获取触摸坐标的,实际上是获取的手指索引为0的位置坐标,当我们放上第二个手指后,这第二个手指的索引为1,此时我们同时滑动这两个手指,会发现没有问题,因为我们追踪的是手指索引为0的手指位置。但是当我们抬起第一个手指后,问题就出现了, 因为这个时候原本索引为1的第二个手指的索引变为了0,所以我们追踪的轨迹就出现了错误。

简单来说,跳动就是因为追踪的手指的改变,而这两个手指之间原本存在间隙,而这个间隙的距离就是我们跳动的距离。

其实问题产生的根本原因就是手指的索引会变化,因此我们需要记录被追踪手指的id,然后当有手指离开屏幕时,判断离开的手指是否是我们正在追踪的手指:

如果不是,忽略;
如果是,则选择一个新的手指作为被追踪手指,并且调整位置记录。
还有一点就是,要处理ACTION_POINTER_UP事件,就需要给action与上一个掩码:event.getAction()&MotionEvent.ACTION_MASK 或者使用 event.getActionMasked()方法。

更改后的onTouchEvent()的实现如下:

@Override
public boolean onTouchEvent(MotionEvent event) {
final int action = event.getActionMasked();
if (velocityTracker == null) {
velocityTracker = VelocityTracker.obtain();
}
velocityTracker.addMovement(event);
switch (action) {
case MotionEvent.ACTION_DOWN:
// 获取索引为0的手指id
mPointerId = event.getPointerId(0);
x = event.getX();
y = event.getY();
if (!mScroller.isFinished())
mScroller.abortAnimation();
break;
case MotionEvent.ACTION_MOVE:
// 获取当前手指id所对应的索引,虽然在ACTION_DOWN的时候,我们默认选取索引为0
// 的手指,但当有第二个手指触摸,并且先前有效的手指up之后,我们会调整有效手指
// 屏幕上可能有多个手指,我们需要保证使用的是同一个手指的移动轨迹,
// 因此此处不能使用event.getActionIndex()来获得索引
final int pointerIndex = event.findPointerIndex(mPointerId);
float mx = event.getX(pointerIndex);
float my = event.getY(pointerIndex);
moveBy((int) (x - mx), (int) (y - my));
x = mx;
y = my;
break;
case MotionEvent.ACTION_UP:
velocityTracker.computeCurrentVelocity(1000, maxFlingVelocity);
float velocityX = velocityTracker.getXVelocity(mPointerId);
float velocityY = velocityTracker.getYVelocity(mPointerId);
completeMove(-velocityX, -velocityY);
if (velocityTracker != null) {
velocityTracker.recycle();
velocityTracker = null;
}
break;
case MotionEvent.ACTION_POINTER_UP:
// 获取离开屏幕的手指的索引
int pointerIndexLeave = event.getActionIndex();
int pointerIdLeave = event.getPointerId(pointerIndexLeave);
if (mPointerId == pointerIdLeave) {
// 离开屏幕的正是目前的有效手指,此处需要重新调整,并且需要重置VelocityTracker
int reIndex = pointerIndexLeave == 0 ? 1 : 0;
mPointerId = event.getPointerId(reIndex);
// 调整触摸位置,防止出现跳动
x = event.getX(reIndex);
y = event.getY(reIndex);
if (velocityTracker != null)
velocityTracker.clear();
}
break;
}
return true;
}


好了,现在我们用多个手指交替滑动就很正常了。
我们解决了多个手指交替滑动带来的页面的跳动问题。但同时也还遗留了两个问题。

我们自定义的这个ViewGroup本身还不支持onClick, onLongClick事件。
当我们给子View设置click事件后,我们的ViewGroup居然不能滑动了。
相对来讲,第一个问题稍稍容易处理一点,这里我们先说一下第二个问题。

onInterceptTouchEvent()的作用以及何时会被调用

onInterceptTouchEvent()是用来给ViewGroup自己一个拦截事件的机会,当ViewGroup意识到某个Touch事件应该由自己处理,那么就可以通过此方法来阻止事件被分发到子View中。

为什么onInterceptTouchEvent()方法只接收到来ACTION_DOWN事件??需要处理ACTION_MOVE,ACTION_UP等等事件吗??

按照google官方文档的说明:

如果onInterceptTouchEvent方法返回true,那么它将不会收到后续事件,事件将会直接传递给目标的onTouchEvent方法(其实会先传给目标的onTouch方法);
如果onInterceptTouchEvent方法返回false,那么所有的后续事件都会先传给onInterceptTouchEvent,然后再传给目标的onTouchEvent方法。
但是,为什么我们在onInterceptTouchEvent方法中返回false之后,却收不到后续的事件呢??通过实验以及stackoverflow上面的一些问答得知,当我们在onInterceptTouchEvent()方法中返回false,且子View的onTouchEvent返回true的情况下,onInterceptTouchEvent方法才会收到后续的事件。

虽然这个结果与官方文档的说法有点不同,但实验说明是正确的。仔细想想这样的逻辑也确实非常合理:因为onInterceptTouchEvent方法是用来拦截触摸事件,防止被子View捕获。那么现在子View在onTouchEvent中返回false,明确声明自己不会处理这个触摸事件,那么这个时候还需要拦截吗?当然就不需要了,因此onInterceptTouchEvent不需要拦截这个事件,那也就没有必要将后续事件再传给它了。

还有就是onInterceptTouchEvent()被调用的前提是它的子View没有调用requestDisallowInterceptTouchEvent(true)方法(这个方法用于阻止ViewGroup拦截事件)。

ViewGroup的onInterceptTouchEvent方法,onTouchEvent方法以及View的onTouchEvent方法之间的事件传递流程

画了一个简单的图,如下:

其中:Intercept指的是onInterceptTouchEvent()方法,Touch指的是onTouchEvent()方法。

好了,现在我们可以解决博客开头列出的第二个问题了,之所以为子View设置click之后,我们的ViewGroup方法无法滑动,是因为,子View在接受到ACTION_DOWN事件后返回true,并且ViewGroup的onInterceptTouchEvent()方法的默认实现是返回false(就是完全不拦截),所以后续的ACTION_MOVE,ACTION_UP事件都传递给了子View,因此我们的ViewGroup自然就无法滑动了。

解决方法就是重写onInterceptTouchEvent方法:

/**
* onInterceptTouchEvent()用来询问是否要拦截处理。 onTouchEvent()是用来进行处理。
*
* 例如:parentLayout----childLayout----childView 事件的分发流程:
* parentLayout::onInterceptTouchEvent()---false?--->
* childLayout::onInterceptTouchEvent()---false?--->
* childView::onTouchEvent()---false?--->
* childLayout::onTouchEvent()---false?---> parentLayout::onTouchEvent()
*
*
*
* 如果onInterceptTouchEvent()返回false,且分发的子View的onTouchEvent()中返回true,
* 那么onInterceptTouchEvent()将收到所有的后续事件。
*
* 如果onInterceptTouchEvent()返回true,原本的target将收到ACTION_CANCEL,该事件
* 将会发送给我们自己的onTouchEvent()。
*/
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
final int action = ev.getActionMasked();
if (BuildConfig.DEBUG)
Log.d("onInterceptTouchEvent", "action: " + action);
if (action == MotionEvent.ACTION_DOWN && ev.getEdgeFlags() != 0) {
// 该事件可能不是我们的
return false;
}
boolean isIntercept = false;
switch (action) {
case MotionEvent.ACTION_DOWN:
// 如果动画还未结束,则将此事件交给onTouchEvet()处理,
// 否则,先分发给子View
isIntercept = !mScroller.isFinished();
// 如果此时不拦截ACTION_DOWN时间,应该记录下触摸地址及手指id,当我们决定拦截ACTION_MOVE的event时,
// 将会需要这些初始信息(因为我们的onTouchEvent将可能接收不到ACTION_DOWN事件)
mPointerId = ev.getPointerId(0);
// if (!isIntercept) {
downX = x = ev.getX();
downY = y = ev.getY();
// }
break;
case MotionEvent.ACTION_MOVE:
int pointerIndex = ev.findPointerIndex(mPointerId);
if (BuildConfig.DEBUG)
Log.d("onInterceptTouchEvent", "pointerIndex: " + pointerIndex
+ ", pointerId: " + mPointerId);
float mx = ev.getX(pointerIndex);
float my = ev.getY(pointerIndex);
if (BuildConfig.DEBUG)
Log.d("onInterceptTouchEvent", "action_move [touchSlop: "
+ mTouchSlop + ", deltaX: " + (x - mx) + ", deltaY: "
+ (y - my) + "]");
// 根据方向进行拦截,(其实这样,如果我们的方向是水平的,里面有一个ScrollView,那么我们是支持嵌套的)
if (orientation == Orientation.HORIZONTAL) {
if (Math.abs(x - mx) >= mTouchSlop) {
// we get a move event for ourself
isIntercept = true;
}
} else {
if (Math.abs(y - my) >= mTouchSlop) {
isIntercept = true;
}
}
//如果不拦截的话,我们不会更新位置,这样可以通过累积小的移动距离来判断是否达到可以认为是Move的阈值。
//这里当产生拦截的话,会更新位置(这样相当于损失了mTouchSlop的移动距离,如果不更新,可能会有一点点跳的感觉)
if (isIntercept) {
x = mx;
y = my;
}
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
// 这是触摸的最后一个事件,无论如何都不会拦截
if (velocityTracker != null) {
velocityTracker.recycle();
velocityTracker = null;
}
break;
case MotionEvent.ACTION_POINTER_UP:
solvePointerUp(ev);
break;
}
return isIntercept;
}
private void solvePointerUp(MotionEvent event) {
// 获取离开屏幕的手指的索引
int pointerIndexLeave = event.getActionIndex();
int pointerIdLeave = event.getPointerId(pointerIndexLeave);
if (mPointerId == pointerIdLeave) {
// 离开屏幕的正是目前的有效手指,此处需要重新调整,并且需要重置VelocityTracker
int reIndex = pointerIndexLeave == 0 ? 1 : 0;
mPointerId = event.getPointerId(reIndex);
// 调整触摸位置,防止出现跳动
x = event.getX(reIndex);
y = event.getY(reIndex);
if (velocityTracker != null)
velocityTracker.clear();
}
}


现在再运行app,问题应该解决了。
onTouchEvent收到ACTION_DOWN,是否一定能收到ACTION_MOVE,ACTION_UP...???     收到了ACTION_MOVE,能否说明它已经收到过ACTION_DOWN???

其实根据上面所说的onInterceptTouchEvent方法与onTouchEvent方法之间事件传递的过程,我们知道这两个问题的答案都是否定的。

对于第一个,收到ACTION_DOWN事件后,ACTION_MOVE事件可能会被拦截,那么它将只能够再收到一个ACTION_CANCEL事件。

对于第二个,是基于上面的这一个情况,ACTION_DOWN传递给了子View,而onInterceptTouchEvent拦截了ACTION_MOVE事件,所以我们的onTouchEvent方法将会收到ACTION_MOVE,而不会收到ACTION_DOWN。(这也是为什么我在onInterceptTouchEvent方法的ACTION_DOWN中记录下位置信息的原因)

还有一个问题就是,如果我们单纯的在onTouchEvent中: 对于ACTION_DOWN返回true,在接收到ACTION_MOVE事件后返回false,那么这个时候事件会重新寻找能处理它的View吗?不会,所有的后续事件依然会发给这个onTouchEvent方法。


让ViewGroup支持click事件

这里我们是在onTouchEvent中对于ACTION_UP多做了一些处理:

判断从按下时的位置到现在的移动距离是否小于可被识别为Move的阈值。
根据ACTION_DOWN和ACTION_UP之间的时间差,判断是CLICK,还是LONG CLICK(这里当没有设置long click的话,我们也可将其认为是click)

case MotionEvent.ACTION_UP:
//先判断是否是点击事件
final int pi = event.findPointerIndex(mPointerId);
if((isClickable() || isLongClickable())
&& ((event.getX(pi) - downX) < mTouchSlop || (event.getY(pi) - downY) < mTouchSlop)) {
//这里我们得到了一个点击事件
if(isFocusable() && isFocusableInTouchMode() && !isFocused())
requestFocus();
if(event.getEventTime() - event.getDownTime() >= ViewConfiguration.getLongPressTimeout() && isLongClickable()) {
//是一个长按事件
performLongClick();
} else {
performClick();
}
} else {
velocityTracker.computeCurrentVelocity(1000, maxFlingVelocity);
float velocityX = velocityTracker.getXVelocity(mPointerId);
float velocityY = velocityTracker.getYVelocity(mPointerId);
completeMove(-velocityX, -velocityY);
if (velocityTracker != null) {
velocityTracker.recycle();
velocityTracker = null;
}
}
break;

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Android ViewGroup