之所以写这个,是不太了解源码是怎么解决Touch事件和点击事件冲突,看了之后才知道,原来还是自己知识太浅薄了。先看看源码:
package com.example.administrator.mytest;
import android.content.Context;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.widget.ImageView;
/**
* Created by Jim on 2016/10/17.
*/
public class LHImageView extends ImageView {
private ScaleGestureDetector scaleGestureDetector;
private GestureDetector doubleGestureDetector;
public LHImageView(Context context, AttributeSet attrs) {
super(context, attrs);
scaleGestureDetector=new ScaleGestureDetector(context,new ScaleListener());//手势的声明,着重用于图片缩放
doubleGestureDetector=new GestureDetector(context,new OnGestureListener());//手势的声明,用于单点击双点击
super.setOnTouchListener(new PrivateOnTouchListener());
}
private class PrivateOnTouchListener implements OnTouchListener{
@Override
public boolean onTouch(View v, MotionEvent event) {
scaleGestureDetector.onTouchEvent(event);
doubleGestureDetector.onTouchEvent(event);
//做相应的事件,着重用于图片的拖动
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
}
class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
public ScaleListener() {
super();
}
@Override
public boolean onScale(ScaleGestureDetector detector) {
System.out.println("=====onScale====");
return super.onScale(detector);
}
@Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
System.out.println("=====onScaleBegin====");
return super.onScaleBegin(detector);
}
@Override
public void onScaleEnd(ScaleGestureDetector detector) {
System.out.println("=====onScaleEnd====");
super.onScaleEnd(detector);
}
}
class OnGestureListener extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
System.out.println("=====onSingleTapConfirmed====");
return performClick();//Call this view's OnClickListener(调用这个View的OnClickListener事件)
}
@Override
public boolean onDoubleTap(MotionEvent e) {
System.out.println("=====onDoubleTap====");
return super.onDoubleTap(e);
}
@Override
public void onLongPress(MotionEvent e) {
performLongClick();//Call this view's OnLongClickListener
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return super.onScroll(e1, e2, distanceX, distanceY);
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return super.onFling(e1, e2, velocityX, velocityY);
}
@Override
public boolean onDown(MotionEvent e) {
return super.onDown(e);
}
}
}
关键点:项目用到了两个手势:ScaleGestureDetector 和 GestureDetector,ScaleGestureDetector 用于图片的缩放,GestureDetector这里着重用于图片的单击和双击,至于拖动则是在OnTouchListener中实现的。关于他们的回调函数,注释已经写的很详细了。这里,我就不多讲了。上面代码,只是TouchImage的一个大体框架。具体的TouchImage的链接地址如下:http://download.csdn.net/detail/jimtrency/9656431