Language/Android Studio

[Android] 안드로이드 기본 이벤트 처리 | Yoon's Dev

Yooniron 2021. 6. 13. 21:18

안드로이드 기본 이벤트 처리

(클릭, 포커스, 롱 클릭, 키, 터치)

 


 


사용자 간의 상호작용을 위한 간단한 이벤트 처리 과정

( 한 화면에 여러 이벤트가 존재하는 다중 이벤트 처리)

 


 

기본 이벤트 종류

 

■ 클릭

✓ OnClickListener

   . void onCLick(View v)

 

■ 포커스 변경

✓ OnFocusChangeListener

   . void onFocusChange(View v, boolean hasFocus)

 

■ 롱클릭

✓ OnLongClickListener

   . Boolean onCLick(View v)

 

■ 키 (특정 위치를 사용하는 경우)

✓ OnKeyListener

   . Boolean onKey(View v, int KeyCode, KeyEvent event)

   . onKeyDown(int keyCode, KeyEvent event) // 특정 위치를 사용하지 않는 경우

 

■ 터치

✓ OnTouchListener

   . Boolean onTouch(View v, MotionEvent event)

 

KEY CODE

 

*키 코드 가운데 숫자, 알파벳 등의 입력은 안드로이드 버전에 따라 인식이 제한됨*

 

 KEYCODE_DPAD_LEFT 왼쪽 화살표

 KEYCODE_DPAD_RIGHT 오른쪽 화살표

 KEYCODE_DPAD_UP 위쪽 화살표

 KEYCODE_DPAD_DOWN 아래쪽 화살표

 KEYCODE_DPAD_CENTER 중앙 버튼

 KEYCODE_CALL 통화 버튼

 KEYCODE_ENDCALL 통화 종료 버튼

 KEYCODE_HOME 홈 버튼

 KEYCODE_BACK 뒤로 가기 버튼

 KEYCODE_BOLUME_UP 볼륨 업 버튼

 KEYCODE_BOLUME_DOWN 볼륨 다운 버튼

 KEYCODE_0 ~ KEYCODE_9 숫자 0 ~ 9

 KEYCODE_A ~ KEYCODE_Z 알파벳 A ~ Z

 

 

 

1. EventTest 레이아웃 구성

 

다음과 같은 화면을 작성해봅시다.

activity_main.xml

 

Component Tree

 

 

 

activity_main.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
 
 
    <androidx.constraintlayout.widget.Guideline
 
        android:id="@+id/v_gline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.50" />
 
 
    <Button
 
        android:id="@+id/button01"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:text="Click / LongClick"
        android:textAllCaps="false"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
 
 
    <EditText
 
        android:id="@+id/editText01"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:ems="10"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button01" />
 
 
    <EditText
 
        android:id="@+id/editText02"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:ems="10"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText01">
 
        <requestFocus />
 
 
    </EditText>
 
 
    <TextView
 
        android:id="@+id/textView01"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="8dp"
        android:background="#BDBDBD"
        android:text="TouchEvent Test"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText02" />
 
 
</androidx.constraintlayout.widget.ConstraintLayout>
cs

 


 

2. Java Class 파일(기능 구현)

 

MainActivity.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
package com.examples.eventtest;
 
import androidx.appcompat.app.AppCompatActivity;
 
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
 
public class MainActivity extends AppCompatActivity implements View.OnClickListener,
                                                                View.OnLongClickListener,
                                                                View.OnFocusChangeListener,
//                                                                View.OnKeyListener,
                                                                View.OnTouchListener {
 
    Button btn01, btn02;
    EditText edit01, edit02;
    TextView text01;
 
    /* Gesture Detector 추가 */
 
    GestureDetector gDetector;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        btn01 = (Button) findViewById(R.id.button01);
        btn01.setOnClickListener(this);
        btn01.setOnLongClickListener(this);
 
//        btn02 = (Button) findViewById(R.id.button02);
//        btn02.setOnLongClickListener(this);
 
        edit01 = (EditText) findViewById(R.id.editText01);
        edit01.setOnFocusChangeListener(this);
 
        edit02 = (EditText) findViewById(R.id.editText02);
//        edit02.setOnKeyListener(this);
 
        text01 = (TextView) findViewById(R.id.textView01);
        text01.setOnTouchListener(this);
 
        //GestureDetector 추가 부분
 
        gDetector = new GestureDetector(thisnew GestureDetector.OnGestureListener() {
            @Override
            public boolean onDown(MotionEvent e) {
                //터치하려고 손을 대는 순간
                return false;
            }
 
            @Override
            public void onShowPress(MotionEvent e) {
                //터치하면 호출, 일정시간 누르는 경우
            }
 
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                //한번 터치가 확실한 경우 호출
                return false;
            }
 
            @Override
            public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
                // 드래그 하면...
                return false;
            }
 
            @Override
            public void onLongPress(MotionEvent e) {
                // 길게 누르면
            }
 
            @Override
            public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
                // 드래그하다가 떼면...
                return false;
            }
        });
 
    }
 
    @Override
    public void onClick(View v) {
        Toast.makeText(this"onClick!", Toast.LENGTH_LONG).show();
    }
 
    @Override
    public boolean onLongClick(View v) {
        Toast.makeText(this"onLongClick!", Toast.LENGTH_LONG).show();
        return false;
    }
 
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        String s = "";
        if (hasFocus) {
            ((EditText) v).setText("");
        } else {
            s = edit01.getText().toString();
            edit01.setText(s + "+ focus change");
        }
    }
 
//    @Override
//    public boolean onKey(View v, int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            Toast.makeText(this, "KEYCODE_BACK", Toast.LENGTH_LONG).show();
//        }
//        if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
//            text01.setText("Volume Up");
//        }
//        if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
//            text01.setText("Volume Down");
//        }
//        return false;
//    }
 
 
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
            text01.setText("Volume Up");
        }
        if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
            text01.setText("Volume Down");
        }
        return super.onKeyDown(keyCode, event);
    }
 
    // back 키
    @Override
    public void onBackPressed() {
        super.onBackPressed(); // 주석처리하면 Back키 안먹음
        Toast.makeText(this"BACK", Toast.LENGTH_SHORT).show();
    }
    
    // Home 키
    @Override
    protected void onUserLeaveHint() {
        super.onUserLeaveHint();
        Toast.makeText(this"홈키", Toast.LENGTH_SHORT).show();
    }
 
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
//            text01.setText("ACTION_DOWN");
            return true;
        }
        if (event.getAction() == MotionEvent.ACTION_MOVE) {
//            text01.setText("ACTION_MOVE");
 
            //상대좌표
            float x = event.getX();
            float y = event.getY();
 
            //절대좌표
            float rawX = event.getRawX();
            float rawY = event.getRawY();
 
            text01.setText("X: " + x + "\nY: " + y
                    + "\n\nrawX: " + rawX + "\nrawY: " + rawY);
 
            return false;
        }
        if (event.getAction() == MotionEvent.ACTION_UP) {
//            text01.setText("ACTION_UP");
            return false;
        }
 
        gDetector.onTouchEvent(event);
        return false;
    }
}
cs

 

 


 

3. 실행결과

 

 실행 화면

처음 실행 화면

 

onClick

클릭 시

 

 onLongClick

롱 클릭

 

 onFocusChnage

Focus Change

 

 onTouch

onTouch

 

 onKeyDown

KeyDown