Android Programming

[Mobile Programming] 터치 이벤트

gangintheremark 2021. 10. 18. 22:20
728x90

터치 이벤트

  • 뷰의 콜백 메소드 재정의 : 커스텀 뷰를 정의하고 onTouchEvent() 재정의
  • 리스너 등록을 통한 터치 이벤트 처리
class MyView extends View {
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        x = (int) event.getX();  // 터치 지점의 위치 정보 필요 
        y = (int) event.getY();
        ...
    }
}

터치 이벤트 종류

Event에 들어있는 action code

  • ACTION_DOWN : 누르는 동작 시작
  • ACTION_UP : 누르고 있다가 뗄 때 발생
  • ACTION_MOVE : 누르는 도중 움직임
  • ACTION_CANCEL : 터치 동작 취소
  • ACTION_OUTSIDE : 터치가 현재의 위젯 벗어남

터치 이벤트 예제

  • 누르고 있을 때나 누르고 움직일 때는 빨간색 원으로 위치 표시
  • 뗼 때 파란색 원으로 위치 표시
public class MainActivity extends AppCompatActivity {

    class MyCustomView extends View {
        int x,y;  // 변수 선언
        boolean drawObject = false; // true 상태는 move , false 상태는 멈춘상태

        //생성자 ( 클래스와 같은이름 )
        public MyCustomView(Context mycon){ 
            super(mycon);
            setBackgroundColor(Color.YELLOW); // 생성자에서 미리 화면의 색깔을 지정할 수 있음
        }

        //이벤트처리함수 재정의
        @Override  
        public boolean onTouchEvent(MotionEvent event) { 
            x = (int) event.getX(0);
            y = (int) event.getY(0);

            if(event.getAction() == MotionEvent.ACTION_DOWN)
                drawObject = true;
            else if(event.getAction() == MotionEvent.ACTION_MOVE)
                drawObject = true;
            else if(event.getAction() == MotionEvent.ACTION_UP)
                drawObject = false;

            invalidate();
            return true; 
        }

        //화면에 그리는 그림
        protected void onDraw(Canvas canvas) {
            Paint mypaint = new Paint();
            mypaint.setTextSize(50);
            mypaint.setColor(Color.RED);
            if(drawObject)
                canvas.drawCircle(x,y,50,mypaint);
            else {
                mypaint.setColor(Color.BLUE);
                canvas.drawCircle(x,y,50,mypaint);
            }
        }
}

728x90