How do I detect touch input on the Android

前端 未结 5 1481
無奈伤痛
無奈伤痛 2020-12-05 11:18

Right now all I am trying to do is detect when the screen is pressed and then display a log message to confirm it happened. My code so far is modified off of the CameraPrevi

5条回答
  •  情歌与酒
    2020-12-05 11:55

    Here is a simple example on how to detect a simple on touch event, get coords and show a toast. The event in this exmple are Action Down, Move and Action up.

    import android.app.Activity;
    import android.os.Bundle;
    import android.view.MotionEvent;
    import android.widget.Toast;
    
    public class MainActivity extends Activity {
    
        private boolean isTouch = false;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        }
    
        @Override
        public boolean onTouchEvent(MotionEvent event) {
    
            int X = (int) event.getX();
            int Y = (int) event.getY();
            int eventaction = event.getAction();
    
            switch (eventaction) {
                case MotionEvent.ACTION_DOWN:
                    Toast.makeText(this, "ACTION_DOWN AT COORDS "+"X: "+X+" Y: "+Y, Toast.LENGTH_SHORT).show();
                    isTouch = true;
                    break;
    
                case MotionEvent.ACTION_MOVE:
                    Toast.makeText(this, "MOVE "+"X: "+X+" Y: "+Y, Toast.LENGTH_SHORT).show();
                    break;
    
                case MotionEvent.ACTION_UP:
                    Toast.makeText(this, "ACTION_UP "+"X: "+X+" Y: "+Y, Toast.LENGTH_SHORT).show();
                    break;
            }
            return true;
        }
    }
    

提交回复
热议问题