확인해 볼까? 이벤트...

18
public boolean onTouchEvent(MotionEvent event) { swtich(event.getAction()) { case MotionEvent.ACTION_DOWN: //화면을 터치하였을 때 6차시 이벤트 처리 1 학습목표 ❍ 터치 이벤트 처리를 배운다. ❍ XML의 onClick 속성을 사용하여 이벤트를 처리한다. 2 확인해 볼까? 3 이벤트 처리하기 1) 학습하기 ❍ 터치 이벤트

Upload: others

Post on 15-Oct-2020

3 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 확인해 볼까? 이벤트 처리하기elearning.kocw.net/contents4/document/lec/2013/Mokwon/Leesang… · 안드로이드 기본 - 7 - 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

public boolean onTouchEvent(MotionEvent event) {

swtich(event.getAction()) {

case MotionEvent.ACTION_DOWN: //화면을 터치하였을 때

6차시 이벤트 처리

1 학습목표

❍ 터치 이벤트 처리를 배운다. ❍ XML의 onClick 속성을 사용하여 이벤트를 처리한다.

2 확인해 볼까?

우리가 사용하는 안드로이드 앱은 바탕화면을 터치하거나 버튼을 누르면 어떤 동작

을 수행한다. 어떻게 하면 이런 기능을 넣을 수 있을까?

3 이벤트 처리하기

1) 학습하기 안드로이드 폰은 그래픽 사용자 인터페이스 (GUI)를 채택하여 터치 스크린을

사용하고 있다. 안드로이드 응용프로그램은 사용자가 화면에 터치와 같은 액션을

취하면 적절한 이벤트를 처리해주어야 한다. 안드로이드에서 이벤트를 처리하는

방법은 매우 다양하지만 가장 많이 사용하는 화면의 터치 이벤트와 위젯의 클릭

이벤트에 대해 자세히 알아보도록 하겠다.

❍ 터치 이벤트사용자가 안드로이드 폰 화면을 터치하면 터치 이벤트가 발생한다. 이러한 터

치 이벤트를 구현하려면 View 클래스의 onTouchEvent() 메소드를 오버라이딩 하

여 원하는 기능을 코딩하면 된다. 일반적인 사용 형태는 다음과 같다.

Page 2: 확인해 볼까? 이벤트 처리하기elearning.kocw.net/contents4/document/lec/2013/Mokwon/Leesang… · 안드로이드 기본 - 7 - 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

안드로이드 기본

- 2 -

// 화면을 터치하였을 때 해야할 작업 구현

break;

case MotionEvent.ACTION_MOVE: //화면을 드래그하였 때

// 화면을 드래그하였을 때 해야할 작업 구현

break;

case MotionEvent.ACTION_UP: //화면에서 터치가 사라질 때

// 화면에서 터치가 사라질 때 해야할 자업 구현

break;

case MotionEvent.ACTION_CANCEL: //터치가 취소될 때

// 터치가 취소될 때 해야할 작업 구현

break;

default:

break;

}

return true;

}

[예제 6-1]터치이벤트.java1

2

3

4

5

package com.example.프로젝트명;

import android.app.Activity;import android.content.Context;import android.graphics.Canvas;

화면을 터치하면 event.getAction()으로 터치한 동작을 얻은 후, 그에 따라

switch 문으로 분기하여 해당 액션에 대해 처리해야 할 작업을 수행한다. 이전 장

에서 도형을 그리기 위해 XY좌표를 직접 코드에 집어넣었지만 사용자가 터치한

점을 터치이벤트를 처리를 통해 입력받는다면 손가락으로 화면을 터치하여 그림

을 그릴 수 있다. 다음 예제를 통해 확인해 보자.

새로운 안드로이드 프로젝트를 만들고 이름은 임의로 정한다. 프로젝트 생성 과정은

2차시 ‘활동 과정: 안드로이드 응용 프로그램 작성해보기’의 (3)~(6)의 과정을 따른다.

화면 전체를 커스텀 뷰로 사용할 때는 레이아웃을 사용하지 않으므로 main.xml 파일

은 지워도 무방하다. Package Explorer에서 [프로젝트명]-[src]-[com.example.프로젝트

명]-[프로젝트명Activity.java] 파일을 열고 아래와 같이 코딩한다.

Page 3: 확인해 볼까? 이벤트 처리하기elearning.kocw.net/contents4/document/lec/2013/Mokwon/Leesang… · 안드로이드 기본 - 7 - 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

안드로이드 기본

- 3 -

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

import android.graphics.Color;import android.graphics.Paint;import android.os.Bundle;import android.view.MotionEvent;import android.view.View;

public class 프로젝트명Activity extends Activity {

@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);

MyView myView = new MyView(this); setContentView(myView); }

public class MyView extends View {

public MyView(Context context) { super(context); }

float centerX = 0; float centerY = 0; float radius = 0;

@Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: centerX = event.getX(); centerY = event.getY(); break; case MotionEvent.ACTION_MOVE: radius = (float) Math.sqrt((event.getX() - centerX)

* (event.getX() - centerX) + (event.getY() - centerY)* (event.getY() - centerY));

this.invalidate(); break; case MotionEvent.ACTION_UP:

Page 4: 확인해 볼까? 이벤트 처리하기elearning.kocw.net/contents4/document/lec/2013/Mokwon/Leesang… · 안드로이드 기본 - 7 - 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

안드로이드 기본

- 4 -

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

radius = (float) Math.sqrt((event.getX() - centerX)* (event.getX() - centerX) + (event.getY() - centerY)* (event.getY() - centerY));

this.invalidate(); break; } return true; }

@Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); Paint paint = new Paint(); paint.setAntiAlias(true); paint.setColor(Color.BLUE);

canvas.drawCircle(centerX, centerY, radius, paint); } }}

18, 19행 main.xml 파일 대신 재정의한 커스텀 뷰인 MyView클래스를 화면에 보여준다.

22행 커스텀 뷰 정의를 시작하는 부분이다. View를 상속받아 MyView 클래스를 재정의한다.

View에 에러가 나면 "Ctrl + Shift + O"를 눌러 View 클래스를 임포트한다.

24~26행 생성자를 재정의 하는 부분이다. 22행의 빨간줄이 그인 MyView에 마우스커서를 가

져간 후 [Add Constructor 'MyView(Context)']를 선택한다.

28~30행 원의 중심점과 반지름에 대한 변수를 선언하고 초기화 한다.

33~53행 onTouchEvent() 메소드를 재정의한다. MyView 안의 빈공간에 마우스 커서를 데고,

마우스 오른쪽 버튼을 눌러 [Source]-[Override/Implement Methods...] 팝업 메뉴를 선택

한다. [Override/Implement Methods] 대화상자가 나오면 [onTouchEvent(MotionEvent

event)]를 체크하고 <OK>버튼을 클릭하여 추가한 후 코딩한다.

35~38행 터치된 화면의 점의 좌표를 (centerX, centerY)에 저장한다.

40~43행, 46~49행 화면이 드래그 될 때와 화면에서 손을 떼었을 때 반지름을 계산한다.

invalidate() 메소드를 수행하면 onDraw() 메소드가 수행되어 화면을 다시 그려준다.

56~62행 onDraw() 메소드를 재정의한다. MyView 안의 빈공간에 마우스 커서를 데고, 마우스

오른쪽 버튼을 눌러 [Source]-[Override/Implement Methods...] 팝업 메뉴를 선택한다.

[Override/Implement Methods] 대화상자가 나오면 [onDraw(Canvas)]를 체크하고 <OK>

버튼을 클릭하여 추가한 후 코딩한다. 원을 그려주는 모듈이 들어가 있다.

코드를 실행해보자. 빈 바탕화면에 마우스 왼쪽 버튼을 클릭한 후 드래그하여

이동하여 보자. [그림 6-1]과 같이 파랑색 원이 그려지는 것을 확인할 수 있을 것

Page 5: 확인해 볼까? 이벤트 처리하기elearning.kocw.net/contents4/document/lec/2013/Mokwon/Leesang… · 안드로이드 기본 - 7 - 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

안드로이드 기본

- 5 -

[예제 6-2]main.xml1

2

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"

이다.

[그림 6-1] 실행 화면

❍ 위젯 클릭 이벤트이번에는 위젯의 클릭 이벤트에 대해 알아보자. 가장 많이 사용하는 위젯 클릭

이벤트는 버튼 클릭 이벤트이다. 지금까지 많은 예제에서 버튼 위젯에 대한 클릭

이벤트 처리를 해주었다. 클릭은 터치와 다르게 눌렀다 떼는 동작에 대한 이벤트

이며 터치에 의해 추가로 발생하는 높은 수준의 이벤트이다. 이벤트를 처리하는

방법은 여러 가지이나 흔하게 사용하는 두 가지의 경우를 살펴보자.

익명 이너 클래스의 임시 객체를 활용한 이벤트 처리

지금까지 우리가 버튼에 대한 이벤트 처리를 위해 사용했던 방법이다. 아래의

예제를 통해 살펴보자.

새로운 안드로이드 프로젝트를 만들고 이름은 임의로 정한다. 프로젝트 생성 과정은

2차시 ‘활동 과정: 안드로이드 응용 프로그램 작성해보기’의 (3)~(6)의 과정을 따른다.

Package Explorer에서 [프로젝트명]-[res]-[layout]-[main.xml] 파일을 열고 아래와 같이

코딩한다.

Page 6: 확인해 볼까? 이벤트 처리하기elearning.kocw.net/contents4/document/lec/2013/Mokwon/Leesang… · 안드로이드 기본 - 7 - 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

안드로이드 기본

- 6 -

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

android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".프로젝트명Activity" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center_horizontal" android:orientation="horizontal" > <Button android:id="@+id/btnRed" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Red" /> <Button android:id="@+id/btnGreen" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Green" /> <Button android:id="@+id/btnBlue" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Blue" /> </LinearLayout> <TextView android:id="@+id/tvText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text="Color" android:textSize="20dp" /></LinearLayout>

[예제 6-3]프로젝트명Activity.java

Package Explorer에서 [프로젝트명]-[src]-[com.example.프로젝트명]-[프로젝트명

Activity.java] 파일을 열고 아래와 같이 코딩한다.

Page 7: 확인해 볼까? 이벤트 처리하기elearning.kocw.net/contents4/document/lec/2013/Mokwon/Leesang… · 안드로이드 기본 - 7 - 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

안드로이드 기본

- 7 -

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

package com.example.프로젝트명;

import android.app.Activity;import android.graphics.Color;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView;

public class 프로젝트명Activity extends Activity {

Button btnRed, btnGreen, btnBlue; TextView tvText;

@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);

btnRed = (Button) findViewById(R.id.btnRed); btnGreen = (Button) findViewById(R.id.btnGreen); btnBlue = (Button) findViewById(R.id.btnBlue); tvText = (TextView) findViewById(R.id.tvText);

btnRed.setOnClickListener(new View.OnClickListener() {

@Override public void onClick(View arg0) { tvText.setTextColor(Color.RED); tvText.setText("Red"); } }); btnGreen.setOnClickListener(new View.OnClickListener() {

@Override public void onClick(View arg0) { tvText.setTextColor(Color.GREEN); tvText.setText("Green"); } });

Page 8: 확인해 볼까? 이벤트 처리하기elearning.kocw.net/contents4/document/lec/2013/Mokwon/Leesang… · 안드로이드 기본 - 7 - 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

안드로이드 기본

- 8 -

41

42

43

44

45

46

47

48

49

50

btnBlue.setOnClickListener(new View.OnClickListener() {

@Override public void onClick(View arg0) { tvText.setTextColor(Color.BLUE); tvText.setText("Blue"); } }); }}

[그림 6-2] 실행 화면

위 예제는 3개의 Red, Green, Blue 버튼을 클릭하면 아래의 텍스트뷰에 버튼에

해당하는 색상으로 색상을 출력한다. 3개의 버튼이 변수 값만 다르고 같은 동작

을 하므로 중복된 코드가 많다. 이러한 중복된 코드를 없애는 방법 중에 하나가

XML의 onClick 속성을 이용하는 것이다.

XML의 onClick 속성을 활용한 이벤트 처리

클릭은 너무나도 자주 발생하는 이벤트이다. 그래서 SDK 1.6부터는 자주 사용

하는 클릭 이벤트에 대해서 XML 문서에 onClick 속성으로 리스너를 등록할 수

있도록 하였다. 클릭 이벤트를 XML에서 등록하는 방법은 android:onClick = "이

벤트처리메소드이름"을 사용하면 된다. 다음 예제를 살펴보자.

앞서 실습한 [예제 6-2]의 main.xml에서 3개의 Button 속성에 android: onClick

= "onClick"을 다음과 같이 모두 추가한다.

Page 9: 확인해 볼까? 이벤트 처리하기elearning.kocw.net/contents4/document/lec/2013/Mokwon/Leesang… · 안드로이드 기본 - 7 - 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

안드로이드 기본

- 9 -

[예제 6-4]main.xml1

2

3

4

5

6

7

8

~~~~ 중간 생략 ~~~~~ <Button android:id="@+id/btnRed" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="onClick" android:text="Red" />~~~~ 중간 생략 ~~~~~

6행 버튼 위젯에 onClick 속성을 설정하였다. 동일한 방법으로 2개의 버튼에도 설정한다. 프로

그램을 실행하여 버튼을 클릭하면 onClick() 메소드가 호출된다.

[예제 6-5]프로젝트명Activity.java1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

package com.example.프로젝트명;

import android.app.Activity;import android.graphics.Color;import android.os.Bundle;import android.view.View;import android.widget.TextView;

public class 프로젝트명Activity extends Activity {

TextView tvText;

@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); }

public void onClick(View v) { switch (v.getId()) { case R.id.btnRed: tvText.setTextColor(Color.RED);

XML에서 onClick 속성을 지정하였다면, Java 코드에는 지정한 메소드를 만들

어줘야 한다. public void 이벤트처리메소드이름 (View v)와 같은 형식으로 만들

면 된다. 아래 예제를 통해 실습해 보자.

Page 10: 확인해 볼까? 이벤트 처리하기elearning.kocw.net/contents4/document/lec/2013/Mokwon/Leesang… · 안드로이드 기본 - 7 - 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

안드로이드 기본

- 10 -

23

24

25

26

27

28

29

30

31

32

33

34

35

tvText.setText("Red"); break; case R.id.btnGreen: tvText.setTextColor(Color.GREEN); tvText.setText("Green"); break; case R.id.btnBlue: tvText.setTextColor(Color.BLUE); tvText.setText("Blue"); break; } }}

17~32행 XML에서 설정한 onClick 속성에 대한 메소드를 구현하였다.

18행 v.getID() 메소드를 통해 버튼의 ID를 가져와 어떤 버튼이 클릭되었는지 알수 있다.

코드 완성 후 실행하면 [그림 6-2]와 같이 동일한 결과를 얻는 것을 확인할 수

있다.

2) 활동하기 ❍ 활동 개요이번 활동에서는 터치 이벤트와 XML의 onClick 속성을 이용하여 간단한 그림

판을 구현한다. 버튼으로 도형의 모형 및 색상을 정하고 그림판에 터치 및 드래

그를 통해 그림을 그릴 수 있도록 한다.

❍ 활동 과정(1) 새로운 안드로이드 프로젝트를 만들고 이름은 Event로 한다. 프로젝트 생성 과정

은 2차시 ‘활동 과정: 안드로이드 응용 프로그램 작성해보기’의 (3)~(6)의 과정을 따른

다.

(2) 커스텀 뷰를 위젯으로 만든다. 프로젝트의 [src]-[패키지명]에 마우스 오른쪽 버튼

을 클릭하고 [New]-[Class]를 선택한다. [Java Class] 창이 나오면 Name에 “MyView”

라고 입력한다. Superclass에는 “android.view.View”를 입력하고 <Finish>를 클릭한다.

Page 11: 확인해 볼까? 이벤트 처리하기elearning.kocw.net/contents4/document/lec/2013/Mokwon/Leesang… · 안드로이드 기본 - 7 - 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

안드로이드 기본

- 11 -

[예제 6-6]MyView.java1

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

package com.example.event;

import android.content.Context;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.util.AttributeSet;import android.view.MotionEvent;import android.view.View;

public class MyView extends View {

public MyView(Context context, AttributeSet attrs) { super(context, attrs); }

final static int LINE = 1, CIRCLE = 2, RECT = 3; static int shape = LINE; static int color = Color.RED; float startX = 0; //시작점 X좌표

float startY = 0; //시작점 Y좌표

float endX = 0; //끝점 X좌표

float endY = 0; //끝점 Y좌표

float radius = 0; //반지름

@Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: startX = event.getX(); startY = event.getY();

(3) Package Explorer의 MyView.java를 더블클릭하면 MyView에 빨간 줄이 그어져

있는데, MyView에 마우스를 가져간 후 [Add Constructor 'MyView(Context,

AttributeSet)']를 선택한다.

(4) onDraw() 메소드를 오버라이딩하고, 다음과 같이 코딩한다.

Page 12: 확인해 볼까? 이벤트 처리하기elearning.kocw.net/contents4/document/lec/2013/Mokwon/Leesang… · 안드로이드 기본 - 7 - 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

안드로이드 기본

- 12 -

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

break; case MotionEvent.ACTION_MOVE: case MotionEvent.ACTION_UP: endX = event.getX(); endY = event.getY(); this.invalidate(); break; } return true; }

@Override protected void onDraw(Canvas canvas) { super.onDraw(canvas);

Paint paint = new Paint(); paint.setColor(color);

switch(shape){ case LINE: canvas.drawLine(startX, startY, endX, endY, paint); break; case CIRCLE: radius = (float) Math.sqrt((startX - endX)

* (startX - endX) + (startY - endY)* (startY - endY));

canvas.drawCircle(startX, startY, radius, paint); break; case RECT: canvas.drawRect(startX, startY, endX, endY, paint); break; } }}

17행 도형 모형에 대한 상수값 선언

18행 도형의 값을 저장하는 정적변수를 선언하고 초기화한다.

19행 페인트 색상의 값을 저장하는 정적변수를 선언하고 초기화한다.

(5) Package Explorer에서 [Event]-[res]-[layout]-[main.xml] 파일을 열고, [main.xml]

Page 13: 확인해 볼까? 이벤트 처리하기elearning.kocw.net/contents4/document/lec/2013/Mokwon/Leesang… · 안드로이드 기본 - 7 - 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

안드로이드 기본

- 13 -

[예제 6-7]main.xml1

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".EventActivity" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <Button android:id="@+id/btnLine" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:onClick="onClick" android:text="선그리기" /> <Button android:id="@+id/btnCircle" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:onClick="onClick" android:text="원그리기" /> <Button android:id="@+id/btnRect" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1"

탭을 클릭하여 화면을 구성한다. 화면 구성은 다음과 같다.

. RelativeLayout을 LinearLayout으로 변경하고 orientation을 vertical로 설정한다.

. 큰 LinearLayout 내부에 LinearLayout 2개, 커스텀 위젯으로 구성한다.

. 내부 LinearLayout들의 orientation을 horizontal로 설정하고, 각각 Button 3개로

구성한다. 버튼들이 화면에 꽉 차도록 layout_weight 설정을 해준다.

. 마지막 커스텀 위젯이 남은 화면에 꽉 차도록 layout_weight 설정을 해준다.

Page 14: 확인해 볼까? 이벤트 처리하기elearning.kocw.net/contents4/document/lec/2013/Mokwon/Leesang… · 안드로이드 기본 - 7 - 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

안드로이드 기본

- 14 -

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

android:onClick="onClick" android:text="사각형" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <Button android:id="@+id/btnRed" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:onClick="onClick" android:text="빨강" /> <Button android:id="@+id/btnGreen" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:onClick="onClick" android:text="초록" /> <Button android:id="@+id/btnBlue" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:onClick="onClick" android:text="파랑" /> </LinearLayout> <com.example.event.MyView android:id="@+id/myView" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" /></LinearLayout>

(6) Package Explorer에서 [Event]-[src]-[com.example.event]-[EventActivity. java] 파일

을 연다. onCreateOptionsMenu() 메소드는 사용하지 않으므로 관련 부분을 삭제한다.

Page 15: 확인해 볼까? 이벤트 처리하기elearning.kocw.net/contents4/document/lec/2013/Mokwon/Leesang… · 안드로이드 기본 - 7 - 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

안드로이드 기본

- 15 -

[예제 6-8]EventActivity.java1

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

packge com.example.event;

import android.app.Activity;import android.graphics.Color;import android.os.Bundle;import android.view.View;import android.widget.TextView;

public class EventActivity extends Activity {

TextView tvText;

@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); }

public void onClick(View v) { switch (v.getId()) { case R.id.btnRed: MyView.color = Color.RED; break; case R.id.btnGreen: MyView.color = Color.GREEN; break; case R.id.btnBlue: MyView.color = Color.BLUE; break; case R.id.btnLine: MyView.shape = MyView.LINE; break; case R.id.btnCircle: MyView.shape = MyView.CIRCLE; break; case R.id.btnRect: MyView.shape = MyView.RECT; break; }

Page 16: 확인해 볼까? 이벤트 처리하기elearning.kocw.net/contents4/document/lec/2013/Mokwon/Leesang… · 안드로이드 기본 - 7 - 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

안드로이드 기본

- 16 -

40

41

}}

public boolean onTouchEvent(MotionEvent event) {

swtich(event.getAction()) {

case MotionEvent.ACTION_DOWN: //화면을 터치하였을 때

// 화면을 터치하였을 때 해야할 작업 구현

break;

case MotionEvent.ACTION_MOVE: //화면을 드래그하였 때

// 화면을 드래그하였을 때 해야할 작업 구현

break;

(7) 프로젝트를 실행하여 결과를 확인한다. [그림 6-3]과 같이 동작할 것이다.

[그림 6-3] 실행 화면

4 배운 내용 정리

1) 화면에 터치하였을 때의 이벤트를 처리하려면 다음과 같은 onTouchEvent()를 오버

라이딩해야 한다.

Page 17: 확인해 볼까? 이벤트 처리하기elearning.kocw.net/contents4/document/lec/2013/Mokwon/Leesang… · 안드로이드 기본 - 7 - 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

안드로이드 기본

- 17 -

case MotionEvent.ACTION_UP: //화면에서 터치가 사라질 때

// 화면에서 터치가 사라질 때 해야할 자업 구현

break;

case MotionEvent.ACTION_CANCEL: //터치가 취소될 때

// 터치가 취소될 때 해야할 작업 구현

break;

default:

break;

}

return true;

} 2) 여러 위젯의 중복된 클릭 이벤트는 XML의 onClick 속성을 사용하여 중복된 코드를

줄일 수 있다.

5 학습 확인하기

1) XML에서 리스너 등록이 가능한 이벤트는 무엇인지 답하라.

2) 다음의 onTouchEvent() 메소드의 이벤트를 연결하라.

MotionEvent 사용자 이벤트

① ACTION_DOWN② ACTION_MOVE③ ACTION_UP④ ACTION_CANCEL

연결해 보자

ⓐ 화면에서 드래그 함

ⓑ 화면에서 손을 땜

ⓒ 화면을 터치함

ⓓ 화면 터치를 취소함

6 지식창고

❍ 참고문헌[1] 우재남, 이복기, “안드로이드 프로그래밍”, 한빛미디어, 2012

[2] 김상형, “안드로이드 프로그래밍 정복”, 한빛미디어, 2011

Page 18: 확인해 볼까? 이벤트 처리하기elearning.kocw.net/contents4/document/lec/2013/Mokwon/Leesang… · 안드로이드 기본 - 7 - 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

안드로이드 기본

- 18 -

❍ 참고사이트[1] http://developer.android.com/

[2] http://developer.android.com/reference