Skip to content Skip to sidebar Skip to footer

Android Press Longclicklistener Get X, Y Coordinates, Ontouchlistener

I have a button and want to use a LongClickListener, to get by pressing on the button the coordinates during changing the position of the button. How can I get in a LongClickListen

Solution 1:

do it like here in OnTouchListener:

OnTouchListenermOnTouch=newOnTouchListener()
{
    @OverridepublicbooleanonTouch(View v, MotionEvent event)
    {            
       finalintaction= ev.getAction();
       switch (action & MotionEvent.ACTION_MASK) {
       case MotionEvent.ACTION_DOWN: {
          finalintx= (int) ev.getX();
          finalinty= (int) ev.getY();
       break;
    }
};

Solution 2:

You have to store the last known coordinates as found in onTouch somewhere (global data for example) and read them in your onLongClick method.

You may also have to use onInterceptTouchEvent in some cases.

Solution 3:

The solution is to

  • Add a class variable to store the coordinates
  • Save the X,Y coordinates using an OnTouchListener
  • Access the X,Y coordinates in the OnLongClickListener

The other two answers leave out some details that might be helpful, so here is a full demonstration:

publicclassMainActivityextendsAppCompatActivity {

    // class member variable to save the X,Y coordinatesprivatefloat[] lastTouchDownXY = newfloat[2];

    @OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // add both a touch listener and a long click listenerViewmyView= findViewById(R.id.my_view);
        myView.setOnTouchListener(touchListener);
        myView.setOnLongClickListener(longClickListener);
    }

    // the purpose of the touch listener is just to store the touch X,Y coordinates
    View.OnTouchListenertouchListener=newView.OnTouchListener() {
        @OverridepublicbooleanonTouch(View v, MotionEvent event) {

            // save the X,Y coordinatesif (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
                lastTouchDownXY[0] = event.getX();
                lastTouchDownXY[1] = event.getY();
            }

            // let the touch event pass on to whoever needs itreturnfalse;
        }
    };

    View.OnLongClickListenerlongClickListener=newView.OnLongClickListener() {
        @OverridepublicbooleanonLongClick(View v) {

            // retrieve the stored coordinatesfloatx= lastTouchDownXY[0];
            floaty= lastTouchDownXY[1];

            // use the coordinates for whatever
            Log.i("TAG", "onLongClick: x = " + x + ", y = " + y);

            // we have consumed the touch eventreturntrue;
        }
    };
}

Solution 4:

@OverridepublicbooleanperformLongClick(float x, float y) {
    super.performLongClick(x, y);
    doSomething();
    returnsuper.performLongClick(x, y);
}

Post a Comment for "Android Press Longclicklistener Get X, Y Coordinates, Ontouchlistener"