检测Android上的ImageView的Click和Touch

时间:2015-10-10 13:44:20

标签: android view onclicklistener ontouchlistener

我有一个名为 fullImage 的ImageView。 我必须同时检测Touch和Click。

问题是,如果同时为同一个ImageView设置了 setOnTouchListener setOnClickListener 也无效。

  

onTouch代码

fullImage.setOnTouchListener(new OnSwipeTouchListener(getBaseContext()) {
    @Override
    public void onSwipeLeft() {

    }

    public void onSwipeRight() {

    }

});
  

onClick代码

fullImage.setOnClickListener(
        new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            Log.d("click status", "click received");

            }
        });

有关如何解决的任何指示?

1 个答案:

答案 0 :(得分:1)

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

public class OnSwipeTouchListener implements OnTouchListener {

private final GestureDetector gestureDetector;

public OnSwipeTouchListener(Context context) {
    gestureDetector = new GestureDetector(context, new GestureListener());
}

public void onSwipeLeft() {
}

public void onSwipeRight() {
}


@SuppressLint("ClickableViewAccessibility")
public boolean onTouch(View v, MotionEvent event) {
    return gestureDetector.onTouchEvent(event);
}

private final class GestureListener extends SimpleOnGestureListener {

    private static final int SWIPE_DISTANCE_THRESHOLD = 100;
    private static final int SWIPE_VELOCITY_THRESHOLD = 100;

    @Override
    public boolean onDown(MotionEvent e) {
        return true;
    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        Log.e("Touch up", "Touch up");
        return super.onSingleTapUp(e);
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        float distanceX = e2.getX() - e1.getX();
        float distanceY = e2.getY() - e1.getY();
        if (Math.abs(distanceX) > Math.abs(distanceY) && Math.abs(distanceX) > SWIPE_DISTANCE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
            if (distanceX > 0)
                onSwipeRight();
            else
                onSwipeLeft();
            return true;
        }

        return false;
    }
}
}