공학영재교재 안드로이드기본 4차시 레이아웃...

19
4차시 레이아웃 1 학습목표 ❍ 레이아웃의 개념을 이해한다. ❍ 중복 리니어레이아웃의 개념 이해한다. 2 확인해 볼까? 3 레이아웃 개념 익히기 1) 학습하기 [그림 4-1] ViewGroup 클래스 계층도

Upload: others

Post on 01-Aug-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 공학영재교재 안드로이드기본 4차시 레이아웃 이상욱elearning.kocw.net/contents4/document/lec/2013/... · 4~17행 첫 번째 내부 리니어레이아웃 18~32행

4차시 레이아웃

1 학습목표

❍ 레이아웃의 개념을 이해한다. ❍ 중복 리니어레이아웃의 개념 이해한다.

2 확인해 볼까?

이전 장에서 배운 기본 위젯들을 사용해서 안드로이드 앱을 만들려고 한다. 구글 플

레이에서 다운 받아 사용하는 앱처럼 버튼, 텍스트박스, 에디트박스 등의 기본위젯들을

화면위에 잘 배치하고 싶다. 어떻게 하면 안드로이드 화면위에 내가 원하는 위치에 위

젯들을 배치할 수 있을까?

3 레이아웃 개념 익히기

1) 학습하기

[그림 4-1] ViewGroup 클래스 계층도

Page 2: 공학영재교재 안드로이드기본 4차시 레이아웃 이상욱elearning.kocw.net/contents4/document/lec/2013/... · 4~17행 첫 번째 내부 리니어레이아웃 18~32행

안드로이드 기본

- 2 -

안드로이드에서 화면에 위젯들을 배치할 때, 텍스트뷰, 버튼, 에디트텍스트 등

의 기본 위젯들은 레이아웃이라는 틀 위에 배치한다. 레이아웃은 ViewGroup 클

래스로부터 상속받으며 ([그림 4-1] 참조), 종류에는 리니어레이아웃(Linear

Layout), 렐러티브레이아웃(RelativeLayout), 테이블레이아웃(TableLayout), 프레임

레이아웃(FrameLayout), 그리드레이아웃(GridLayout) 등이 있다. 기본적으로 레이

아웃은 View 클래스의 하위 클래스이므로 View 클래스의 XML 속성 및 메소드

를 모두 사용할 수 있다. 여러 가지의 레이아웃들 중 가장 많이 사용되는 리니어

레이아웃에 대해 자세히 알아보자.

❍ 리니어레이아웃안드로이드 프로젝트를 생성하면 main.xml 파일이 만들어진다. 안드로이드

SDK 4.0.0 이전의 버전에서는 기본적으로 리니어레이아웃으로 생성되지만 그 이

후 버전부터는 렐러티브레이아웃이 기본적으로 생성된다. 렐러티브레이아웃은

main.xml 파일의 [Graphical Layout]탭에서 마우스로 위젯들을 드래그하여 화면

에 배치할 수 있다. 언뜻 보기에는 렐러티브레이아웃의 GUI 환경을 이용하여 화

면을 구성하는 것이 리니어레이아웃에서 XML 코딩으로 화면을 구성하는 것에

비해 더 쉬워 보인다. 그러나 렐리티브레이아웃은 여러 위젯들의 상대적인 위치

설정을 통해 화면을 구성하므로, 화면 구성 후 어떤 위젯을 삭제하거나 위치를

변경할 경우 다른 위젯들의 배치도 틀어지게 되어 화면 구성 변경이 어려운 단점

이 있다. 이로 인해 안드로이드 개발자들은 아직까지 리니어레이아웃을 가장 많

이 사용한다. main.xml 파일에서 미리 설정된 렐러티브레이아웃을 리니어레이아

웃으로 변경하려면 다음과 같이 변경한다.

<RelativeLayout> <LinearLayout>

~내용~ => ~내용~

</RelativeLayout> </LinearLayout>

지금부터 리니어레이아웃에서 가장 많이 사용되는 속성들에 대해 알아보자.

Page 3: 공학영재교재 안드로이드기본 4차시 레이아웃 이상욱elearning.kocw.net/contents4/document/lec/2013/... · 4~17행 첫 번째 내부 리니어레이아웃 18~32행

안드로이드 기본

- 3 -

[예제 4-1]orientation 속성-horizontal1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

<LinearLayout ~~~~~~~~중간 생략 ~~~~~~~ android:orientation="horizontal"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button1" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button2" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button3" /></LinearLayout>

3행 orientation 속성을 horizontal로 설정하여 버튼들이 왼쪽위에서부터 오른쪽으로 배치된다.

orientation 속성은 디폴트로 horizontal 값을 가지므로 본행을 삭제하여도 동일한 결과가

나온다.

[예제 4-2]orientation 속성-vertical1

2

3

4

5

6

7

<LinearLayout ~~~~~~~~중간 생략 ~~~~~~~ android:orientation="vertical"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button1" />

orientation

orientation 속성은 리니어레이아웃에서 가장 많이 사용되는 속성으로

horizontal과 vertical의 두 가지의 값을 설정할 수 있다. horizontal로 설정하면 리

니어레이아웃 내에 위젯들이 왼쪽위에서부터 오른쪽으로 순서대로 배치되며,

vertical로 설정하면 왼쪽위에서부터 아래쪽으로 순서대로 배치된다. 설정해주지

않으면 디폴트 값으로 horizontal 값을 가지므로 수직방향으로 배치하고자 할 때

는 반드시 orientation 속성을 vertical로 설정해줘야 한다.

Page 4: 공학영재교재 안드로이드기본 4차시 레이아웃 이상욱elearning.kocw.net/contents4/document/lec/2013/... · 4~17행 첫 번째 내부 리니어레이아웃 18~32행

안드로이드 기본

- 4 -

8

9

10

11

12

13

14

15

16

<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button2" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button3" /></LinearLayout>

3행 orientation 속성을 vertical로 설정하여 버튼들이 왼쪽위에서부터 아래방향으로 배치된다.

본행이 없으면 수평방향으로 배치된다.

[예제 4-3]gravity 속성1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

<LinearLayout ~~~~~~~~중간 생략 ~~~~~~~ android:orientation="vertical" android:gravity="center|bottom"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button1" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button2" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button3" /></LinearLayout>

4행 gravity 속성을 가운데 아래에 설정하여 위젯들이 화면의 가운데 아래에 배치되어 있다.

gravity

gravity 속성은 레이아웃 내부 위젯들을 어느 위치에 배치할 것인가를 결정한

다. left, right, center, top, bottom 등의 값을 가질 수 있으며, 두 개의 값을 조합

할 경우 ‘|’ 로 구분하여 설정한다. 값을 설정할 때 띄어쓰기를 하면 오류가 발생

하니 유의하여야 한다.

Page 5: 공학영재교재 안드로이드기본 4차시 레이아웃 이상욱elearning.kocw.net/contents4/document/lec/2013/... · 4~17행 첫 번째 내부 리니어레이아웃 18~32행

안드로이드 기본

- 5 -

[예제 4-4]layout_gravity1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

<LinearLayout ~~~~~~~~중간 생략 ~~~~~~~ android:orientation="vertical"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="left" android:text="Button1" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text="Button2" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="right" android:text="Button3" /></LinearLayout>

7, 12, 17행 위젯에 layout_gravity 속성을 설정하여 자신을 담고 있는 레이아웃에서 본인은

위치를 결정한다.

layout_gravity

layout_gravity 속성은 자신을 담고 있는 레이아웃 또는 뷰 컨테이너 안에서 자

신을 어디에 배치시킬 것인지를 결정한다. 값 설정 방법은 gravity와 동일하다.

중복 레이아웃과 layout_weight

화면을 구성할 때 [그림 4-2]과 같이 위젯들을 수직 또는 수평의 여러 방향으로

배치하고 싶을 때가 있다. 이런 경우 리니어레이아웃 내부에 여러 개의 레이아웃

을 배치하는 중복 레이아웃 형태를 사용한다.

Page 6: 공학영재교재 안드로이드기본 4차시 레이아웃 이상욱elearning.kocw.net/contents4/document/lec/2013/... · 4~17행 첫 번째 내부 리니어레이아웃 18~32행

안드로이드 기본

- 6 -

[예제 4-5]중복 레이아웃1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

<LinearLayout ~~~~~~~~중간 생략 ~~~~~~~ android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:orientation="horizontal" > <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button1" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button2" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#0000FF" android:gravity="center"

[그림 4-2] 안드로이드 프로젝트 구성

Page 7: 공학영재교재 안드로이드기본 4차시 레이아웃 이상욱elearning.kocw.net/contents4/document/lec/2013/... · 4~17행 첫 번째 내부 리니어레이아웃 18~32행

안드로이드 기본

- 7 -

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

android:orientation="vertical" > <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button3" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button4" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#FF0000" android:gravity="center" android:orientation="horizontal" > <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button5" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button6" /> </LinearLayout></LinearLayout>

4~17행 첫 번째 내부 리니어레이아웃

18~32행 두 번째 내부 리니어레이아웃

33~47행 세 번째 내부 리니어레이아웃

6, 20, 35행 바깥의 큰 리니어레이아웃의 orientation 특성이 수직방향으로 3개의 내부 리니어

레이아웃이 수직방향으로 배치된다. 이때 내부 리니어레이아웃의 높이(layout_height 속성)

를 match_parent 값으로 주면 첫 번째 내부 리니어레이아웃만 보이고 그다음 2개의 내부

리니어레이아웃은 안보이게 된다. 그래서 wrap_content 값으로 설정하였다.

[예제 4-5]에서 바깥의 큰 리니어레이아웃 안에 3개의 내부 리니어레이아웃을

배치하여 [그림 4-2]와 같은 화면 구성을 얻으려 하였다. 내부 리니어레이아웃의

layout_height 속성을 wrap_content로 설정하니 큰 화면 아래에 빈 공간이 많이

생긴 것을 볼 수 있다. 리니어레이아웃 배치에서 빈 공간이 발생하지 않도록 하

Page 8: 공학영재교재 안드로이드기본 4차시 레이아웃 이상욱elearning.kocw.net/contents4/document/lec/2013/... · 4~17행 첫 번째 내부 리니어레이아웃 18~32행

안드로이드 기본

- 8 -

[예제 4-6]layout_weight1

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

<LinearLayout ~~~~~~~~중간 생략 ~~~~~~~ android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:gravity="center" android:orientation="horizontal" > <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button1" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button2" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:background="#0000FF" android:gravity="center" android:orientation="vertical" > <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button3" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button4" /> </LinearLayout> <LinearLayout android:layout_width="match_parent"

기위해서는 layout_weight 속성을 사용해야 한다.

Page 9: 공학영재교재 안드로이드기본 4차시 레이아웃 이상욱elearning.kocw.net/contents4/document/lec/2013/... · 4~17행 첫 번째 내부 리니어레이아웃 18~32행

안드로이드 기본

- 9 -

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

android:layout_height="0dp" android:layout_weight="1" android:background="#FF0000" android:gravity="center" android:orientation="horizontal" > <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button5" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button6" /> </LinearLayout></LinearLayout>

3행 바깥의 큰 리니어레이아웃의 orientation 속성 값이 수직이다.

6, 21, 37행 바깥의 큰 리니어레이아웃의 orientation 속성 값이 수직(vertical)일 때

layout_weight 속성을 사용하려면 내부 레이아웃의 layout_height 속성 값을 0dp로 설정해

야 한다. 반대로, 만약 바깥의 큰 리니어레이아웃의 orientation 속성 값이 수평(horizontal)

일 때 layout_weight 속성을 사용하려면 내부 레이아웃의 layout_width 속성 값을 0dp로

설정해야 한다.

7, 22, 38행 3개의 내부 리니어레이아웃 들의 layout_weighty 속성을 1로 주었다. 이는 사용

할 수 있는 전체공간을 모두 활용하여 1:1:1의 비율로 화면에 배치하겠다는 것을 의미한다.

2) 활동하기 ❍ 활동 개요 가장 기본적인 레이아웃인 리니어레이아웃을 사용하여 [그림 4-3]과 같은 간단

한 사칙 연산 계산기를 만들어 보자. 숫자 버튼을 클릭하면 활성화된 에디트텍스

트에 숫자가 적히고 연산 라디오버튼 선택 후 계산하기 버튼을 클릭하면 텍스트

뷰에 계산결과가 나오도록 한다.

Page 10: 공학영재교재 안드로이드기본 4차시 레이아웃 이상욱elearning.kocw.net/contents4/document/lec/2013/... · 4~17행 첫 번째 내부 리니어레이아웃 18~32행

안드로이드 기본

- 10 -

[그림 4-3] 실행 화면

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

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

정을 따른다.

(2) 이클립스의 Package Explorer에서 [LinearLayout]-[res]-[layout]-[main.xml] 파일을

열고, [main.xml] 탭을 클릭하여 화면을 구성한다. 화면 구성은 다음과 같다.

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

. 큰 LinearLayout 내부에 LinearLayout 4개, RadioGroup, Button, TextView로 구

성한다.

. 첫 번째와 두 번째 내부 LinearLayout은 orientation을 horizontal로 설정하고,

TextView, EditText로 구성한다.

. 세 번째와 네 번째 내부 LinearLayout은 orientation을 horizontal로 설정하고,

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

. RadioGroup은 RadioButton 3개로 구성한다.

Page 11: 공학영재교재 안드로이드기본 4차시 레이아웃 이상욱elearning.kocw.net/contents4/document/lec/2013/... · 4~17행 첫 번째 내부 리니어레이아웃 18~32행

안드로이드 기본

- 11 -

[예제 4-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

30

31

32

<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" android:padding="5dp" tools:context=".LayoutActivity" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:orientation="horizontal" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="첫번째 수" /> <EditText android:id="@+id/edtNum1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:hint="첫번째 수를 입력하세요." /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:orientation="horizontal" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="두번째 수" /> <EditText

. 레이아웃에 padding을 적절히 설정하고, 각 위젯에 layout_margin을 적절히 설정

한다.

. 결과를 보여주는 마지막 텍스트 뷰는 글자크기 20dp로 하고 색상을 빨강으로 설

정한다.

Page 12: 공학영재교재 안드로이드기본 4차시 레이아웃 이상욱elearning.kocw.net/contents4/document/lec/2013/... · 4~17행 첫 번째 내부 리니어레이아웃 18~32행

안드로이드 기본

- 12 -

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

android:id="@+id/edtNum2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:hint="두번째 수를 입력하세요." /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:orientation="horizontal" > <Button android:id="@+id/btn1" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="1" /> <Button android:id="@+id/btn2" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="2" /> <Button android:id="@+id/btn3" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="3" /> <Button android:id="@+id/btn4" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="4" /> <Button android:id="@+id/btn5" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="5" />

Page 13: 공학영재교재 안드로이드기본 4차시 레이아웃 이상욱elearning.kocw.net/contents4/document/lec/2013/... · 4~17행 첫 번째 내부 리니어레이아웃 18~32행

안드로이드 기본

- 13 -

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

</LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:orientation="horizontal" > <Button android:id="@+id/btn6" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="6" /> <Button android:id="@+id/btn7" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="7" /> <Button android:id="@+id/btn8" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="8" /> <Button android:id="@+id/btn9" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="9" /> <Button android:id="@+id/btn0" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="0" /> </LinearLayout> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content"

Page 14: 공학영재교재 안드로이드기본 4차시 레이아웃 이상욱elearning.kocw.net/contents4/document/lec/2013/... · 4~17행 첫 번째 내부 리니어레이아웃 18~32행

안드로이드 기본

- 14 -

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

android:text="연산자" /> <RadioGroup android:id="@+id/rGroup" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="5dp" > <RadioButton android:id="@+id/rbAdd" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="더하기" /> <RadioButton android:id="@+id/rbSub" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="더하기" /> <RadioButton android:id="@+id/rbMul" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="더하기" /> <RadioButton android:id="@+id/rbDiv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="더하기" /> </RadioGroup> <Button android:id="@+id/btnCalc" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:text="계산하기" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="계산결과: " android:textColor="#FF0000" android:textSize="20dp" /></LinearLayout>

Page 15: 공학영재교재 안드로이드기본 4차시 레이아웃 이상욱elearning.kocw.net/contents4/document/lec/2013/... · 4~17행 첫 번째 내부 리니어레이아웃 18~32행

안드로이드 기본

- 15 -

45, 51, 57, 63, 69행 5개의 버튼을 담고 있는 리니어레이아웃의 orientation 속성이 42행처럼

수평으로 설정되어 있고, 수평으로 5개의 버튼을 배열할 때 빈 공간이 발생하지 않도록

layout_weight를 사용하기 위하여 5개 버튼 위젯들의 layout_width 속성을 모두 0dp로 설

정한다.

46, 52, 58, 64, 70행 5개의 버튼이 수평방향으로 1:1:1:1:1의 비율로 배치하도록 한다.

[예제 4-8]LinearLayoutActivity.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

package com.example.linearlayout;

import android.app.Activity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.RadioGroup;import android.widget.TextView;import android.widget.Toast;

public class LinearLayoutActivity extends Activity {

EditText edtNum1, edtNum2; Button[] numButtons = new Button[10]; RadioGroup rGroup; Button btnCalc; TextView tvResult; String strNum1, strNum2; Integer result; Integer[] numButtonIDs = { R.id.btn0, R.id.btn1, R.id.btn2, R.id.btn3, R.id.btn4, R.id.btn5, R.id.btn6, R.id.btn7, R.id.btn8, R.id.btn9 };

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

(3) 이클립스의 Package Explorer에서 [LinearLayout]-[src]-[com.example.

linearlayout]-[LinearLayoutActivity.java] 파일을 연다. onCreateOptionsMenu() 메소드

는 사용하지 않으므로 관련 부분을 삭제한다.

Page 16: 공학영재교재 안드로이드기본 4차시 레이아웃 이상욱elearning.kocw.net/contents4/document/lec/2013/... · 4~17행 첫 번째 내부 리니어레이아웃 18~32행

안드로이드 기본

- 16 -

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

setTitle("간단 사칙연산 계산기");

edtNum1 = (EditText) findViewById(R.id.edtNum1); edtNum2 = (EditText) findViewById(R.id.edtNum2); rGroup = (RadioGroup) findViewById(R.id.rGroup); btnCalc = (Button) findViewById(R.id.btnCalc); tvResult = (TextView) findViewById(R.id.tvResult);

for (int i = 0; i < 10; i++) { numButtons[i] = (Button) findViewById(numButtonIDs[i]); }

for (int i = 0; i < 10; i++) { final int index; index = i;

numButtons[index].setOnClickListener(new View.OnClickListener() {

@Override public void onClick(View v) { if (edtNum1.isFocused() == true) { strNum1 = edtNum1.getText().toString()

+ numButtons[index].getText().toString(); edtNum1.setText(strNum1); } else if (edtNum2.isFocused() == true) { strNum2 = edtNum2.getText().toString()

+ numButtons[index].getText().toString(); edtNum2.setText(strNum2);

} else { Toast.makeText(getApplicationContext(),

"에디트텍스트를 먼저 선택하세요", 0).show(); } } }); }

btnCalc.setOnClickListener(new View.OnClickListener() {

@Override public void onClick(View v) {

Page 17: 공학영재교재 안드로이드기본 4차시 레이아웃 이상욱elearning.kocw.net/contents4/document/lec/2013/... · 4~17행 첫 번째 내부 리니어레이아웃 18~32행

안드로이드 기본

- 17 -

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

switch (rGroup.getCheckedRadioButtonId()) { case R.id.rbAdd: strNum1 = edtNum1.getText().toString(); strNum2 = edtNum2.getText().toString(); result = Integer.parseInt(strNum1) + Integer.parseInt(strNum2); tvResult.setText("계산결과: " + result.toString()); break; case R.id.rbSub: strNum1 = edtNum1.getText().toString(); strNum2 = edtNum2.getText().toString(); result = Integer.parseInt(strNum1) - Integer.parseInt(strNum2); tvResult.setText("계산결과: " + result.toString()); break; case R.id.rbMul: strNum1 = edtNum1.getText().toString(); strNum2 = edtNum2.getText().toString(); result = Integer.parseInt(strNum1) * Integer.parseInt(strNum2); tvResult.setText("계산결과: " + result.toString()); break; case R.id.rbDiv: strNum1 = edtNum1.getText().toString(); strNum2 = edtNum2.getText().toString();

if (Integer.parseInt(strNum2) == 0) Toast.makeText(getApplicationContext(), 0으로 나눌수 없습니다.", 0).show(); else result = Integer.parseInt(strNum1) / Integer.parseInt(strNum2);

tvResult.setText("계산결과: " + result.toString()); break; default: Toast.makeText(getApplicationContext(), "연산을 먼저 선택하세요.", 0).show(); } } }); }}

14~18행 XML의 위젯에 관계되는 변수를 선언한다.

15행 숫자 버튼 10개를 배열로 저장한다.

19행 에디트텍스트에 입력한 문자열 값으로 저장할 변수 선언

Page 18: 공학영재교재 안드로이드기본 4차시 레이아웃 이상욱elearning.kocw.net/contents4/document/lec/2013/... · 4~17행 첫 번째 내부 리니어레이아웃 18~32행

안드로이드 기본

- 18 -

20행 연산결과값을 정수 값으로 저장할 변수 선언

21~22행 숫자 버튼 10개의 id를 배열로 저장한다. (R.java 파일을 참조)

28행 어플리케이션의 제목을 설정한다.

30~38행 XML의 위젯들을 관계되는 변수와 연결한다.

40~62행 숫자 버튼 10개에 대해 클릭했을 때의 동작을 구현한다.

41~42행 i 값을 익명클래스 안에서 사용하기 위해서 final 키워드를 사용하여 선언한 index 변

수를 선언하여 i값을 받는다.

44~61행 각 숫자 버튼에 대해 클릭 이벤트 리스너를 정의한다.

48~59행 숫자 버튼을 클릭했을 때 활성화 되어 있는 에디트텍스트에 숫자를 추가한다. 만약

두 개의 에디트텍스트가 모두 포커싱이 되어 있지않다면 토스트 메시지를 띄운다.

64~102행 계산하기 버튼에 대해 클릭 이벤트 리스너를 정의한다.

68~100행 선택된 연산 라디오버튼에 따라 연산을 수행하도록 switch 문으로 분기한다. 만약

아무런 연산을 선택하지 않았다면 토스트 메시지를 띄운다.

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

4 배운 내용 정리

1) 안드로이드에서 화면을 구성할 때 레이아웃을 사용하여 위젯을 배치한다.

2) 리니어레이아웃의 주요 속성은 다음과 같다.

① orientation: 레이아웃 안에 배치할 위젯의 수직 또는 수평 방향 설정

② gravity: 레이아웃 안에 배치할 위젯의 정렬 방향 설정

③ padding: 레이아웃 안에 배치할 위젯의 여백 설정

④ layout_weight: 레이아웃이 전체 화면에서 차지하는 공간의 가중치 설정

3) 리니어레이아웃에서 중복 레이아웃을 사용하여 위젯의 배치를 가로와 세로를 혼합

한 형태로 화면을 구성할 수 있다.

5 학습 확인하기

1) 리니어레이아웃의 수퍼 클래스는 무엇인지 답하라.

Page 19: 공학영재교재 안드로이드기본 4차시 레이아웃 이상욱elearning.kocw.net/contents4/document/lec/2013/... · 4~17행 첫 번째 내부 리니어레이아웃 18~32행

안드로이드 기본

- 19 -

2) gravity와 layout_gravity의 차이를 간략히 설명하라.

6 지식창고

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

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

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

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