[안드로이드] 이벤트 처리_터치 이벤트, 제스처 이벤트
<이벤트 종류>
- 터치 이벤트
- 제스처 이벤트
- 키 이벤트
: 키패드나 하드웨어 버튼을 누를 때 발생하는 이벤트
- 포커스
: 뷰마다 순서대로 주어지는 포커스
- 화면 방향 변경
: 화면의 방향이 가로/세로로 바뀜에 따라 발생하는 이벤트
* findViewById로 java파일에서 xml의 View를 연결
<터치 이벤트>
: 화면을 손가락으로 누를 때 발생하는 이벤트
[순서]
1) findViewById로 View를 받아옴
2) view.setOnClickListener (버튼 누를때) 호출
view.setOnTouchListener (view를 touch할 때) 호출
3) setOnTouchListener 의 인수로 new VIew.OnTouchListener() 작성 -> onTouch 메서드 자동 작성
-> 손가락을 터치하면, onTouch메서드가 호출됨
4) 상태에 따라 실행할 코드 작성
: 손가락을 눌렀을 때 (ACTION_DOWN)
누른 상태에서 움직일 때 (ACTION_MOVE)
손가락을 뗄 때 (ACTION_UP)
*모션 이벤트 event.getAction을 integer 값으로 액션 상태를 알 수 있음
(코드) activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<View //onTouch메서드 예시
android:id="@+id/view1"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#5DB7FF"/>
<View //
android:id="@+id/view2"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#C4A3FF" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<TextView //실행결과 보여주는 곳
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</ScrollView>
</LinearLayout>
(코드) MainActivity.java
public class MainActivity extends AppCompatActivity {
TextView textView;
View view1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//(1) findViewById로 View를 받아옴
textView = (TextView) findViewById(R.id.textView); //View를 리턴하므로 TextView로 cast전환
view1 = findViewById(R.id.view1);
//(2) view.setOnTouchListener (view를 touch할 때) 호출
view1.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction(); //action을 받는 메서드
float curX = event.getX();
float curY = event.getY();
if(action == MotionEvent.ACTION_DOWN){ //(3) 손가락을 눌렀을 때 실행할 코드
textView.append("ACTION_DOWN ("+ curX + "," + curY +")\n");
}else if(action == MotionEvent.ACTION_MOVE){ //(4) 손가락을 움직일 때 실행할 코드
textView.append("ACTION_MOVE ("+ curX + "," + curY +")\n");
}else if(action == MotionEvent.ACTION_UP){ //(5) 손가락을 뗄 때 실행할 코드
textView.append("ACTION_UP ("+ curX + "," + curY +")\n");
}
return true;
}
});
}
}
-> 결과
<제스처 이벤트>
: 터치 이벤트 중에서 일정 패턴을 만들어 내는 이벤트
(터치 이벤트가 얼마나 빠른 속도로 움직이는지 등을 자동 계산할 때 사용)
[순서]
1) onCreate 외부에 GestureDetector 객체 선언
GestureDetector detector;
2) detector에 new GestureDetector()
*첫 파라미터 : Activity
detector = new GestureDetector(this, new GestureDetector.OnGestureListener(){
... }
3) GestureDetector 내부의 다양한 메서드 활용
- onDown(MotionEvent e)
- onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
: 속도를 자동을 계산해서 파라미터로 넘겨줌
- onLongPress(MotionEvent e)
- onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY)
- onShowPress(MotionEvent e)
- onSingleTapUp(MotionEvent e)
(참고) https://developer.android.com/reference/android/view/GestureDetector.OnGestureListener
4) onTouch내부에 detector.onTouchEvent(event)호출
(코드) activity_main.xml -> 위 예제와 동일
(코드) MainActivity.java
package com.example.practicingprj;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textView;
View view2;
GestureDetector detector; //(1) onCreate 외부에 GestureDetector 객체 선언
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
view2 = findViewById(R.id.view2);
view2.setOnTouchListener(new View.OnTouchListener() {
@Override
//(4) onTouch내부에 detector.onTouchEvent(event)호출
public boolean onTouch(View v, MotionEvent event) {
detector.onTouchEvent(event);
return true;
}
});
//(2) detector에 new GestureDetector()
detector = new GestureDetector(this, new GestureDetector.OnGestureListener() {
//(3) GestureDetector 내부의 다양한 메서드 활용
@Override
public boolean onDown(@NonNull MotionEvent e) {
textView.append("onDown : view가 눌렸음\n");
return true;
}
@Override
public void onShowPress(@NonNull MotionEvent e) {
textView.append("onShowPress : view를 눌렀다 뗌\n");
}
@Override
public boolean onSingleTapUp(@NonNull MotionEvent e) {
textView.append("onSingleTapUp : 짧게 눌렀음\n");
return true;
}
@Override
public boolean onScroll(@NonNull MotionEvent e1, @NonNull MotionEvent e2, float distanceX, float distanceY) {
textView.append("onScroll : 손가락을 끌었음\n");
return true;
}
@Override
public void onLongPress(@NonNull MotionEvent e) {
textView.append("onLongPress : 길게 눌렀음\n");
}
@Override
public boolean onFling(@NonNull MotionEvent e1, @NonNull MotionEvent e2, float velocityX, float velocityY) { //
textView.append("onFling : 이동속도 계산 ("+ velocityX + "," + velocityY +")\n");
return true;
}
});
}
}
-> 결과