How can i get both OnClick and OnTouch Listeners

2019-02-16 04:05发布

问题:

I am in a position to implement different actions for OnClick and OnTouch listeners for an ImageView.I have referred several links in stackoverflow but couldn't achieve my goal. how can I implement this.I've referred

how to use both Ontouch and Onclick for an ImageButton?

Android onTouch with onClick and onLongClick

Can't handle both click and touch events simultaneously

OnTouch/OnClick listeners. Use both?

actually my context was when i click on imageview it will goto other activity and when i swipe on it it has to liked by the user. any help.

回答1:

@Override
    public boolean onTouch(View v, MotionEvent event) {

        System.out.println("ajay +event.getAction()" + event.getAction());
        switch (event.getAction()) {
            case MotionEvent.ACTION_MOVE:
                layOutParams.x = initialX + (int) (event.getRawX() - initialTouchX);
                layOutParams.y = initialY + (int) (event.getRawY() - initialTouchY);

                break;
            case MotionEvent.ACTION_DOWN:
                initialX = layOutParams.x;
                initialY = layOutParams.y;
                initialTouchX = event.getRawX();
                initialTouchY = event.getRawY();
                if (initialTouchX == event.getRawX() && initialTouchY == event.getRawY()) {
                    return false;// to handle Click
                }
                break;
            case MotionEvent.ACTION_UP:
                if (initialTouchX == event.getRawX() && initialTouchY == event.getRawY()) {
                    return false;// to handle Click
                }
                break;

        }
        return true;

    }
};    

onClick Implemenation

overLayview.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            System.out.println("ajay onClick Lisner");
        }
    });


回答2:

You dont need to implement both behaviors, define MIN_SWIPE_DISTANCE and check at ACTION_UP in onTouch, so you will have something like this.

pseudo

private static final int MIN_SWIPE_DISTANCE=300;
private int oldX,newX;

public boolean onTouch(View v, MotionEvent event)
{
    if(event.getAction()==MotionEvent.ACTION_DOWN) // touch down
    {   oldX = event.getX(); //get touch position      }

    else if(event.getAction()==MotionEvent.ACTION_UP) // touch up
    {
       newX = event.getX(); //get last touch position 
       if (Math.abs( newX-oldX )> MIN_SWIPE_DISTANCE)
           //its a swipe
       else
           // its a click
     }
}


回答3:

I think you will need to decide if the gesture is a swipe or not and act acrodingly

see here how to achieve it https://stackoverflow.com/a/938657/1393632