OnClickListener - x,y location of event?

后端 未结 4 2217
难免孤独
难免孤独 2020-11-28 09:28

I have a custom view derived from View. I\'d like to be notified when the view is clicked, and the x,y location of where the click happened. Same for long-clicks.

L

4条回答
  •  不知归路
    2020-11-28 10:00

    Full example

    The other answers are missing some details. Here is a full example.

    public class MainActivity extends AppCompatActivity {
    
        // class member variable to save the X,Y coordinates
        private float[] lastTouchDownXY = new float[2];
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            // add both a touch listener and a click listener
            View myView = findViewById(R.id.my_view);
            myView.setOnTouchListener(touchListener);
            myView.setOnClickListener(clickListener);
        }
    
        // the purpose of the touch listener is just to store the touch X,Y coordinates
        View.OnTouchListener touchListener = new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
    
                // save the X,Y coordinates
                if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
                    lastTouchDownXY[0] = event.getX();
                    lastTouchDownXY[1] = event.getY();
                }
    
                // let the touch event pass on to whoever needs it
                return false;
            }
        };
    
        View.OnClickListener clickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // retrieve the stored coordinates
                float x = lastTouchDownXY[0];
                float y = lastTouchDownXY[1];
    
                // use the coordinates for whatever
                Log.i("TAG", "onLongClick: x = " + x + ", y = " + y);
            }
        };
    }
    

    Summary

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

提交回复
热议问题