Android之间的冲突,OnTouchListener SimpleOnGestureListener和setOnClickListener

时间:2015-07-11 16:04:37

标签: java android android-layout android-fragments android-animation

我正在尝试制作动画:

用例: 1.用户向右(水平)滑动/拖动项目,项目被添加到篮子中。如果他再次滑动,它会在篮子中添加一个相同的项目。 2.用户滑动/拖动项目向左(水平),项目从篮子中移除,如果之前添加,如果篮子中没有项目,我们将其保留原样。

拖动效果:当用户拖动时,项目会随手指一起移动。一旦他离开,物品就会回到原位。

缩放效果:当用户点击该项目时,项目会变焦,让用户知道该项目已添加到购物篮中。 (右拖的复制方法)。

我特意为此目的使用OnSwipeTouchListener Class:

import android.content.Context;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

import PointF;

public class OnSwipeTouchListener implements OnTouchListener {

    private final GestureDetector gestureDetector;
    PointF DownPT = null;
    PointF StartPT = null;
    float startX;
    float startY;

    public OnSwipeTouchListener(Context context , float x, float y) {
        gestureDetector = new GestureDetector(context, new GestureListener());
        DownPT = new PointF();
        StartPT = new PointF();
        this.startX = x;
        this.startY = y;
    }

    public void onSwipeLeft() {
    }

    public void onSwipeRight() {
    }

    public boolean onTouch(View v, MotionEvent event) {

        int eid = event.getAction();

        switch (eid) {
            case MotionEvent.ACTION_MOVE:

                PointF mv = new PointF(event.getX() - DownPT.x, event.getY() - DownPT.y);

                v.setX((int) (StartPT.x + mv.x));
                v.setY(this.startY);
                StartPT = new PointF(v.getX(), v.getY());
                break;
            case MotionEvent.ACTION_DOWN:
                DownPT.x = event.getX();
                DownPT.y = event.getY();
                StartPT = new PointF(v.getX(), v.getY());

                break;
            case MotionEvent.ACTION_UP:
                // Move image back to its original position.
                v.setX(this.startX);
                v.setY(this.startY);                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            

                break;
            default:
                v.setX(this.startX);
                v.setY(this.startY);

                break;
        }

        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 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;
        }
    }
}

当My方法OnTouch如下所示时,我的onSwipeRight()和onSwipeLeft()会被触发,但是当我在代码中实现onTouch时,这两种方法不会被触发

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

关于Click事件的缩放效果。

在我的片段中,我正在缩放这样的图像。

offerimg1.setOnClickListener(new View.OnClickListener(){

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            zoomAnimation(v, offerimg1);
        }
    });

我的zoomAnimation方法是:

private void zoomAnimation(View view,ImageView image) {
        Animation animation = AnimationUtils.loadAnimation(getActivity().getApplicationContext(), R.anim.zoom);
        image.startAnimation(animation);
    }

My Zoom正在工作,除非我没有在我的碎片中实现:

 offerimg1.setOnTouchListener(new OnSwipeTouchListener(getActivity().getApplicationContext(),offerimg1.getX(),offerimg1.getY()) {
            @Override
            public void onSwipeLeft() {
                Log.d("onTouch "," swipe left");
            }

            @Override
            public void onSwipeRight() {
                Log.d("onTouch "," swipe right");
            }

        });

我不确定这些事件之间的冲突是什么。我需要实现我的上述用例,每个事件都应该适用于每个图像。由于我的图像位于片段的滚动视图中。

如果您愿意,我可以在这里分享更多代码。如果我无法澄清我的问题,请告诉我。

我非常感谢你的帮助。

此致 Shashank Pratap

1 个答案:

答案 0 :(得分:0)

最后我解决了这个问题,

使用以上代码找到问题

  

onSwipeLeft()和onSwipeRight()..因为我的图像随之移动   我的手指,这就是distanceX显示为零的原因,   它始终小于静态SWIPE_DISTANCE_THRESHOLD。并在   代码我们说如果distanceX为负,则其swipeLeft()else   swipeRight()

解决方案: 我们需要在某种程度上捕获用户移动他/她的手指的方式,因此我决定在MotionEvent.ACTION_MOVE:event中查找mv.x是否为负或mv.x为正。一旦找到它,就很容易做出决定,在此基础上我们可以决定在GestureListener中运行哪种方法。

这是我的OnSwipeTouchListener,我仍然不确定这是否是这种情况的最佳解决方案,但我发现它适用于AVD以及Android设备。

我仍然愿意找到一个很好的,明确的方法(最佳实践):

import android.content.Context;
import android.content.res.Resources;
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;
import android.view.ViewConfiguration;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.Toast;

import R;

import StartingPoints;
import PointF;

public class OnSwipeTouchListener implements OnTouchListener {

    private static final String APP = OnSwipeTouchListener.class.getName() ;
    private final GestureDetector gestureDetector;
    PointF DownPT = null;
    PointF StartPT = null;

    Context _context;
    static  boolean isLeftMoved = false;
    static  boolean isRightMoved = false;

    /**
     * Max allowed duration for a "click", in milliseconds.
     */
    private static final int MAX_CLICK_DURATION = 1000;

    /**
     * Max allowed distance to move during a "click", in DP.
     */
    private static final int MAX_CLICK_DISTANCE = 15;
    private static final float PIXELS_PER_SECOND = 5;

    private long pressStartTime;
    private float pressedX;
    private float pressedY;
    private boolean stayedWithinClickDistance;
    Resources resources;
    private float startX = 0f;
    private float startY = 0f;
    private boolean isNewImage = true;




    public OnSwipeTouchListener(Context context, Resources resources) {
        this._context = context;
        gestureDetector = new GestureDetector(context, new GestureListener());
        DownPT = new PointF();
        StartPT = new PointF();
        this.resources = resources;

    }

    public void onSwipeLeft() {
    }

    public void onSwipeRight() {
    }

    public boolean onTouch(View v, MotionEvent e) {
        if(isNewImage){
            isNewImage = false;
            startX = v.getX();
            startY = v.getY();
        }
        switch (e.getAction()) {
            case MotionEvent.ACTION_DOWN:
                //animation code
                DownPT.x = e.getX();
                DownPT.y = e.getY();
                StartPT = new PointF(v.getX(), v.getY());


                //calculation code
                pressStartTime = System.currentTimeMillis();
                pressedX = e.getX();
                pressedY = e.getY();
                stayedWithinClickDistance = true;
                break;

            case MotionEvent.ACTION_MOVE:
                // animation code
                PointF mv = new PointF(e.getX() - DownPT.x, e.getY() - DownPT.y);
                v.setX((int) (StartPT.x + mv.x));
                v.setY(startY);

                StartPT = new PointF(v.getX(), v.getY());
                if(mv.x < 0 ){
                    isLeftMoved = true;
                }
                if(mv.x > 0 ){
                    isRightMoved = true;
                }

                //calculation code
                if (stayedWithinClickDistance && distance(pressedX, pressedY, e.getX(), e.getY()) > MAX_CLICK_DISTANCE) {
                    stayedWithinClickDistance = false;
                }

                Log.d("Moved ","Item moved");
                break;
            case MotionEvent.ACTION_UP:
                if(!stayedWithinClickDistance){
                    v.setX(startX);
                    v.setY(startY);
                    isNewImage = true;
                }


                long pressDuration = System.currentTimeMillis() - pressStartTime;
                if (pressDuration < MAX_CLICK_DURATION && stayedWithinClickDistance) {
                    // Click event has occurred
                    Log.d("Stayed"," With Click event");
                    zoomAnimation(v);
                    isNewImage = true;
                }


                break;
            default:
                // Move image back to its original position, by default
                Log.d("default", "This is default ");
                v.setX(startX);
                v.setY(startY);
                isNewImage = true;
                break;

        }

        return gestureDetector.onTouchEvent(e);
    }


    private  float distance(float x1, float y1, float x2, float y2) {
        float dx = x1 - x2;
        float dy = y1 - y2;
        float distanceInPx = (float) Math.sqrt(dx * dx + dy * dy);
        return pxToDp(distanceInPx);
    }

    private  float pxToDp(float px) {
        return px / resources.getDisplayMetrics().density;
    }

    private void zoomAnimation(View view) {
        Animation animation = AnimationUtils.loadAnimation(_context, R.anim.zoom);
        view.startAnimation(animation);
    }





    private final class GestureListener extends SimpleOnGestureListener {

        private static final int SWIPE_DISTANCE_THRESHOLD = 20;
        private static final int SWIPE_VELOCITY_THRESHOLD = 50;



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

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {

            float maxFlingVelocity    = ViewConfiguration.get(_context).getScaledMaximumFlingVelocity();
            float velocityPercentX    = velocityX / maxFlingVelocity;          // the percent is a value in the range of (0, 1]
            float normalizedVelocityX = velocityPercentX * PIXELS_PER_SECOND;  // where PIXELS_PER_SECOND is a device-independent measurement

            float distanceX = e2.getX() - e1.getX();
            float distanceY = e2.getY() - e1.getY();

            if (isLeftMoved || isRightMoved) {
                if(isRightMoved) {
                    isLeftMoved = false;
                    isRightMoved = false;
                    onSwipeRight();
                }
                else {
                    isLeftMoved = false;
                    isRightMoved = false;
                    onSwipeLeft();
                }
            }

            return false;
        }

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

祝你好运, Shashank Pratap