ch03. 레이아웃

Download Report

Transcript ch03. 레이아웃

레이아웃 (Layout)
안드로이드 프로그래밍 정복(Android Programming Complete
Guide)
Contents
 학습목표
 뷰와 레이아웃에 대해 이해하고, 레이아웃을 활용, 관리하는 여러 가지
기법들에 대하여 알아본다.
 내용
 뷰 (View)
 리니어 레이아웃 (Linear Layout)
 다른 레이아웃
 레이아웃 관리
2/20
1. 뷰 (View)
 뷰의 계층
 안드로이드 응용 프로그램의 화면을 구성하는 주요 단위인 액티비티는 화면에 직접적으
로 보이지 않으며, 액티비티 안의 뷰가 사용자를 대면하는 실체이다.
 여러 개의 뷰가 모여 하나의 액티비티를 구성하고, 이러한 액티비티가 모여 하나의 응용
프로그램이 된다.
 레이아웃은 액티비티 안에 뷰를 배치하는 기법을 말한다.
 뷰
• 위젯 : 직접적으로 보이며 사용자 인터페이스를 구성하며, 흔히 컨트롤이라고 부른다.
• 뷰 그룹 : 뷰를 담는 컨테이너 역할을 하며, 이 부류의 클래스들을 레이아웃이라고 한다.
 뷰 그룹이면서도 위젯처럼 사용되기도 하는 클래스도 있으며, 특정 위젯을 상세히 알고
싶다면 그 슈퍼 클래스들부터 연구해야 한다.
 서브 클래스는 슈퍼 클래스의 모든 속성을 상속받는다.
3/20
1. 뷰 (View)
 위젯의 계층
 View도 자바 클래스의 일종이므로 루트인 Object로부터 파생된다.
 View로부터 직접 파생되는 모든 클래스가 바로 위젯이며 스스로를 그릴 수 있는 능력을
가지고 있다.
Object
AnalogClock
View
TextView
EditText
EditText
Button
AutoCompleteTextView
CompoundButton
Chronometer
DigitalClock
ImageView
ImageButton
SurfaceView
GLSurfaceView
ProgressBar
CheckBox
RadioButton
ToggleButton
VideoView
SeekBar
AbsSeekBar
RatingBar
4/20
1. 뷰 (View)
 뷰 그룹의 계층
 View로부터 파생된 ViewGroup의 서브 클래스이다.
 다른 뷰들을 차일드로 포함하며 차일드를 정렬하는 기능을 가진다.
Object
FrameLayout
ScrollView, HorizontalScrollView
TabHost, TimePicker, DatePicker
View
ViewAnimator
ViewFlipper
TextSwitcher
ViewSwitcher
ImageSwitcher
ViewGroup
AbsoluteLayout
WebView
RelativeLayout
RadioGroup, ZoomControls
LinearLayout
TableLayout, TableRow
TabWidget
AdapterView
AbsListView
ListView
GridView
AbsSpinner
Spinner
Gallery
5/20
1. 뷰 (View)
 View의 속성
 id
• 뷰를 칭하는 이름을 정의하며, 코드나 XML 문서에서 뷰를 참조할 때 id를 사용하므로 직관적인
이름을 붙이는 것이 좋다.
• 형식 : @[+]id/ID
- @ : id를 리소스(R.java)에 정의하거나 참조한다는 뜻이며, 무조건 붙여야 한다.
- + : ID를 새로 정의한다는 뜻이며, 참조 시는 생략 가능하다.
- id : 예약어
- / : 뒤에 원하는 이름을 작성하되, ID는 고유한 명칭이므로 명령 규칙에 맞아야 하며,
뷰끼리 중복되어서는 안된다.
ex) android:id=“@+id/name” : 텍스트 뷰에 name이라는 id를 부여함.
• XML 문서에 ID를 지정하면 이 이름이 R.java에 정수형 상수로 정의된다.
• 코드에서 뷰를 참조할 시 findViewById 메서드 호출, 인수로 참조할 뷰의 id를 전달한다.
• 모든 뷰에 id를 의무적으로 지정할 필요는 없으며, 코드에서 참조할 필요 없는 위젯은 보통 id를
생략한다.
6/20
1. 뷰 (View)
 View의 속성
 layout_width, layout_height
• 뷰의 폭과 높이를 지정하며, 수평, 수직 각 방향에 대해 크기를 지정할 수 있다.
• 속성값으로 아래의 세 가지 중 하나의 값을 가진다.
- fill_parent : 부모의 주어진 크기를 다 채운다.
- wrap_content : 내용물의 크기만큼만 채운다.
- 정수 크기 : 지정한 크기에 맞춘다.
• ex) “Start”라는 캡션을 가지는 버튼 배치
• 지정한 크기가 액면대로 다 받아들여지지 않으며, 주위 다른 위젯들의 크기에 영향을 받는다.
• 명시적인 크기 지정 시 정수 하나와 단위를 지정하는 예약어를 같이 사용하며, 이 이 단위는 크기
를 지정하는 모든 속성에 공통적으로 적용된다.
• 단위 : px, in, mm, pt, dp (또는 dip), sp (또는 sip)
7/20
1. 뷰 (View)
 View의 속성
 background
• 뷰의 배경을 지정하며, 색상 및 이미지 등의 여러 가지 객체로 지정 가능하다.
• 색상 지정 시 네 가지 형식이 적용되며, 배경뿐만 아니라 색상을 지정하는 모든 속성에 적용된다.
- #RGB
- #ARGB
- #RRGGBB
- #AARRGGBB
ex) #ff0000 (#f00): 빨간색, #0000ff : 파란색
 padding
• 뷰와 내용물간의 간격을 지정한다. (즉 안쪽 여백)
• padding 속성 값을 지정하여 4방향에 대한 여백을 조절할 수 있다.
• 속성값 : paddingLeft, paddingTop, paddingRight, paddingBottom
8/20
1. 뷰 (View)
 View의 속성
 visibility
• 뷰의 표시 유무를 지정하며, 속성값으로 아래의 세 가지 중 하나의 값을 가진다.
- visible : 보이는 상태임.
- invisible : 숨겨진 상태이되 자리는 차지함.
- gone : 숨겨지며 자리도 차지하지 않음.
 clickable, longClickable
• 마우스 클릭 이벤트를 받을 것인지, 롱클릭 이벤트를 받을 것인지를 지정한다.
- click : 손가락으로 뷰를 누름
- longClick: 손가락으로 뷰를 누른 채 잠시 기다림
• 진위형이므로 true 또는 false 둘 중 하나의 값을 지정한다.
 focusable
• 키보드 포커스를 받을 수 있는지를 지정한다.
• 디폴트 값으로 false가 설정되어 있으며, 필요 시 속성을 true로 변경한다.
• 에디트나 버튼처럼 사용자의 입력이 필요한 파생 클래스는 디폴트로 true가 지정되어 있다.
9/20
1. 뷰 (View)
 TextView
 문자열 출력 및 입력받는 위젯
 입력 기능은 숨겨져 있으며 서브 클래스인 EditText에서 활성화된다.
 text
• 텍스트 뷰의 가장 중요한 속성으로 출력할 문자열을 지정한다.
• 리터널 및 리소스로 대입한다.
형식
설명
“문자열”
겹 따옴표로 문자열을 싸서 바로 대입한다. \ 문자가 들어가면 이
스케이프 된다. \n 은 개행이며 \uxxxxx는 유니코드 문자이다.
@[패키지:]type:name
리소스에 대한 레퍼런스로 지정한다. 보통 string.xml에 문자열을
정의해 놓고 @string/id 식으로 지정한다.
?[패키지:][type:]name
테마 속성으로 지정한다.
 textColor
• 문자열의 색상을 지정하며, 디폴트는 불투명한 밝은 회색이다.
• #RRGGBB나 #AARRGGBB 형식으로 각 색상 요소들의 강도를 지정한다.
10/20
1. 뷰 (View)
 TextView
 textSize
• 텍스트의 폰트 크기를 지정하며, 실수 타입으로 지정할 때 숫자 뒤에 sp, dp, px, in, mm 등의 단위
를 같이 지정한다.
 textStyle
• 폰트의 속성을 지정한다.
• normal, bold, italic 중 하나를 쓰거나 ‘|’로 묶어 두 개 이상의 상수값을 지정할 수 있다.
ex: “bold|italic”, “normal|italic”
 typeFace
• 글꼴의 모양을 지정하며, normal, sans, serif, monospace 중 하나로 선택 가능하다.
• 모바일 환경에서 내장된 폰트 개수에 제약이 있다.
 width, height
• 텍스트 뷰의 폭과 높이이며 크기값과 단위를 같이 지정한다.
• 텍스트 뷰는 단독으로 존재하는 경우는 거의 없고 대부분 레이아웃 안에서 차일드로 존재하기 때
문에 이 두 속성은 거의 사용되지 않는다.
11/20
1. 뷰 (View)
 TextView
 singleLine
• 텍스트가 위젯의 폭보다 길 때 강제로 한
줄에 출력한다.
• 속성의 디폴트는 false로 폭보다 더 긴 줄
은 자동으로 아래쪽으로 개행된다.
[ TextView 예제 실행 결과 ]
string.xml
<?xml version=“1.0” encoding=“utf-8”>
<resources>
<string name=“hello”>Hello World, TextViewTest!</string>
<string name=“app_name”>TextViewTest</string>
<string name=“insa”>Hello</string>
<string name=“anyoung”>안녕하세요</string>
</resources>
main.xml
<?xml version=“1.0” encoding=“utf-8”>
<LinearLayout xmlns:android=http://schemas.android.com/apk/res/android
android:orientation=“vertical”
android:layout_width=“fill_parent”
android:layout_height=“fill_parent”>
<TextView
android:layout_width=“fill_parent”
android:layout_height=“wrap_content”
android:text=“@string/insa”
android:textColor=“#ff0000”
android:textSize=“20pt”
android:textStyle=“italic”/>
<TextView
android:layout_width=“fill_parent”
android:layout_height=“wrap_content”
android:text=“@string/anyoung”
android:textSize=“20sp”
android:background=“@0000ff”/>
<TextView
android:layout_width=“fill_parent”
android:layout_height=“wrap_content”
android:text=“Good Morning”
android:textColor=“#8000ff00”
android:textSize=“5mm”
android:typeface=“serif”/>
</LinearLayout>
12/20
1. 뷰 (View)
 ImageView
 아이콘이나 비트맵을 출력하는 위젯으로, 리소스, 파일 등은 물론이고 컨텐트 프로바이
더나 웹 상의 이미지로도 표시 가능하다.
 src
• 출력할 이미지를 지정하는 가장 중요한 속성이다.
• 주로 리소스에 이미지를 복사해 두고 @drawable/ID 형식으로 이미지를 출력하는 방법을 사용한다.
 maxHeight, maxWidth
• 이미지가 출력될 최대 크기를 지정한다.
 adjustViewbounds
• 이미지의 종횡비를 맞추기 위해 이미지 뷰의 크기를 적당히 조정할 것인가를 지정하며, 속성값은
true나 false 중 하나를 사용한다.
 그외
• cropToPadding, tint, scaleType
13/20
1. 뷰 (View)
 ImageView
고해상도 이미지
 jpg, png, gif 등의 이미지 포맷을 지원한
다.
저해상도 이미지
중해상도 이미지
 SDK 1.6 이후 밀도 별로 세 개의 폴더가
존재하며, 해상도 별로 각 폴더에 이미
지를 넣어두면 운영체제가 사용할 이미
지를 결정한다.
Layout/imageviewtest.xml
[ ImageView 예제 실행 결과 ]
<?xml version=“1.0” encoding=“utf-8”>
<LinearLayout xmlns:android=http://schemas.android.com/apk/res/android
android:orientation=“vertical”
android:layout_width=“fill_parent”
android:layout_height=“fill_parent”>
<ImageView
android:layout_width=“fill_parent”
android:layout_height=“wrap_content”
android:src=“@drawable/pride”/>
<ImageView
android:layout_width=“fill_parent”
android:layout_height=“wrap_content”
android:src=“@drawable/pride”
android:maxHeight=“70px”
android:maxWidth=“120px”
android:adjustViewBounds=“true”/>
<ImageView
android:layout_width=“fill_parent”
android:layout_height=“wrap_content”
android:src=“@drawable/dog”
android:tint=“#4000ff00”/>
</LinearLayout>
14/20
1. 뷰 (View)
 Button, Edit
 View, TextView의 서브 클래스이며 고유의 속성은 따로 가지지 않는다.
 Button : 사용자로부터 명령을 입력 받음
 EditText : 문자열을 입력 받음 (에디트)
Layout/buttonedit.xml
<?xml version=“1.0” encoding=“utf-8”>
<LinearLayout xmlns:android=http://schemas.android.com/apk/res/android
android:orientation=“vertical”
android:layout_width=“fill_parent”
android:layout_height=“fill_parent”>
<EditText
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:id=“@+id/edit”
android:text=“여기다 입력”/>
<Button
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:id=“@+id/btn”
android:text=“입력 완료”/>
</LinearLayout>
15/20
2. 리니어 레이아웃
 LinearLayout
 차일드 뷰를 수평, 수직으로 일렬 배치하는 레이아웃으로, 가장 단순하면서 직관적이며
사용빈도가 높다.
 orientation
• 뷰의 배치 방향을 결정하는 속성. (디폴트는 horizontal)
• vertical : 차일드를 위에서 아래로 수직으로 배열
• horizontal : 차일드를 왼쪽에서 오른쪽으로 수평 배열
버튼1
버튼1
버튼2
버튼3
버튼2
버튼3
[ vertical ]
[ horizontal ]
16/20
2. 리니어 레이아웃
 LinearLayout
Layout/Horizontal
<LinearLayout xmlns:android=http://schemas.android.com/apk/res/android
android:orientation=“horizontal”
android:layout_width=“fill_parent”
android:layout_height=“fill_parent” >
[ Horizontal ]
Layout/Horizontal2
<TextView
android:orientation=“horizontal”
android:layout_width=“fill_parent”
android:layout_height=“wrap_content”
android:text=“@string/insa”
android:textColor=“#ff0000”
android:textSize=“20pt”
android:textStyle=“italic”/>
[ Horizontal2 ]
Layout/Horizontal3
<TextView
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:text=“@string/insa”
android:textColor=“#ff0000”
android:textSize=“20pt”
android:textStyle=“italic”/>
[ Horizontal3 ]
17/20
2. 리니어 레이아웃
 gravity
 내용물의 위치를 지정하며, 수평, 수직 방향에 대해 각각 정렬 방식을 지정할 수 있다.
 두 속성을 같이 지정할 때는“|”연산자를 이용하며, 이 때 연산자 양쪽으로 공백이 전혀
없어야 한다.
 각 정렬 방식은 비트 필드로 정의, center, fill은 수평, 수직 정렬 상태 플래그의 조합으
로 정의되어 있다.
상수
값
설명
center_horizontal
0x01
수평으로 중앙에 배치한다.
left
0x03
컨테이너의 왼쪽에 배치하며, 크기는 바뀌지 않는다.
right
0x05
컨테이너의 오른쪽에 배치한다.
fill_horizontal
0x07
수평 방향으로 가득 채운다.
center_vertical
0x10
수직으로 중앙에 배치한다.
top
0x30
컨테이너의 상단에 배치하며, 크기는 바뀌지 않는다.
bottom
0x50
컨테이너의 하단에 배치한다.
fill_vertical
0x70
수직 방향으로 가득 채운다.
center
0x11
수평으로나 수직으로 중앙에 배치한다.
fill
0x77
컨테이너에 가득 채우도록 수직, 수평 크기를 확장한다.
18/20
2. 리니어 레이아웃
 gravity
Layout/gravity1.xml
<?xml version=“1.0” encoding=“utf-8”>
<LinearLayout xmlns:android=http://schemas.android.com/apk/res/android
android:orientation=“vertical”
android:layout_width=“fill_parent”
android:layout_height=“fill_parent” >
<TextView
android:layout_width=“fill_parent”
android:layout_height=“fill_parent”
android:text=“정렬 테스트”
android:textSize=“30pt”
android:textColor=“#00ff00”/>
</LinearLayout>
Layout/gravity2.xml
<TextView
android:layout_width=“fill_parent”
android:layout_height=“fill_parent”
android:text=“정렬 테스트”
android:textSize=“30pt”
android:textColor=“#00ff00”
android:gravity=“center”/>
Layout/gravity3.xml
<TextView
android:layout_width=“fill_parent”
android:layout_height=“fill_parent”
android:text=“정렬 테스트”
android:textSize=“30pt”
android:textColor=“#00ff00”
android:gravity=“center_vertical”/>
19/20
2. 리니어 레이아웃
 gravity
Layout/lgravity1.xml
Layout/lgravity1.xml
<TextView
android:layout_width=“wrap_content”
android:layout_height=“fill_parent”
android:text=“정렬 테스트”
android:textSize=“30pt”
android:textColor=“#00ff00”
android:background=“#ff0000”
android:layout_gravity=“center”/>
<TextView
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:text=“정렬 테스트”
android:textSize=“30pt”
android:textColor=“#00ff00”
android:background=“#ff0000”
android:layout_gravity=“center”/>
[ lgravity1 – width 만 변경 ]
[ lgravity1 – width, height 모두 변경 ]
20/20
2. 리니어 레이아웃
 gravity
Layout/lgravity2.xml
<?xml version=“1.0” encoding=“utf-8”>
<LinearLayout xmlns:android=http://schemas.android.com/apk/res/android
android:orientation=“vertical”
android:layout_width=“fill_parent”
android:layout_height=“fill_parent”
android:gravity=“center” >
<TextView
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:text=“정렬 테스트”
android:textSize=“30pt”
android:textColor=“#00ff00”
android:background=“#ff0000”/>
</LinearLayout>
Layout/lgravity3.xml
[ lgravity2 ]
[ lgravity3 ]
<?xml version=“1.0” encoding=“utf-8”>
<LinearLayout xmlns:android=http://schemas.android.com/apk/res/android
android:orientation=“vertical”
android:layout_width=“fill_parent”
android:layout_height=“fill_parent”
android:gravity=“center” >
<TextView
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:text=“정렬 테스트”
android:textSize=“30pt”
android:textColor=“#00ff00”
android:background=“#ff0000”/>
<Button
android:layout_width=“wrap_content”
android:layout_heigth=“wrap_content”
android:text=“버튼이다.”/>
</LinearLayout>
21/20
2. 리니어 레이아웃
 gravity
Layout/lgravity4.xml
<?xml version=“1.0” encoding=“utf-8”>
<LinearLayout xmlns:android=http://schemas.android.com/apk/res/android
android:orientation=“vertical”
android:layout_width=“fill_parent”
android:layout_height=“fill_parent”
android:gravity=“center” >
<TextView
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:text=“정렬 테스트”
android:textSize=“30pt”
android:textColor=“#00ff00”
android:background=“#ff0000”
android:layout_gravity=“center_horizontal”
android:gravity=“right|bottom”/>
</LinearLayout>
[ lgravity4 ]
22/20
2. 리니어 레이아웃
 baselineAligned
 높이가 다른 차일드 뷰를 수평으로 정렬 시 하단 정렬 지정 (디폴트 true)
Layout/base1.xml ~ base2.xml
<?xml version=“1.0” encoding=“utf-8”>
<LinearLayout xmlns:android=http://schemas.android.com/apk/res/android
android:orientation=“horizontal”
android:layout_width=“fill_parent”
android:layout_height=“fill_parent”
android:baselineAligned=“ture” >
<TextView
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:text=“Medium”
android:textSize=“10pt”/>
<TextView
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:text=“Small”
android:textSize=“5pt”
android:background=“#0000ff”/>
<TextView
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:text=“Large”
android:textSize=“20pt”
android:typeface=“serif”/>
</LinearLayout>
[ base1 ]
[ base2 ]
23/20
2. 리니어 레이아웃
 layout_weight
 중요도에 따라 차일드의 크기를 균등 분할한다.
 중요도가 0이면 자신의 고유한 크기만큼, 1 이상이면 형제 뷰와의 비율에 따라 부모의
영역을 균등하게 배분한다.
Layout/weight1.xml ~ weight2.xml
<?xml version=“1.0” encoding=“utf-8”>
<LinearLayout xmlns:android=http://schemas.android.com/apk/res/android
android:orientation=“vertical”
android:layout_width=“fill_parent”
android:layout_height=“fill_parent”>
<Button
android:layout_width=“fill_parent”
android:layout_height=“wrap_content”
android:text=“위쪽 버튼”
android:layout_weight=“1”/>
<EditText
android:layout_width=“fill_parent”
android:layout_height=“wrap_content”
android:text=“가운데 에디트”
android:layout_weight=“3”/>
<Button
android:layout_width=“fill_parent”
android:layout_height=“wrap_content”
android:text=“아래쪽 버튼”
android:layout_weight=“1”/>
</LinearLayout>
[ weight1 ]
[ weight2 ]
24/20
2. 리니어 레이아웃
 layout_weight
Layout/weight3.xml
<?xml version=“1.0” encoding=“utf-8”>
<LinearLayout xmlns:android=http://schemas.android.com/apk/res/android
android:orientation=“vertical”
android:layout_width=“fill_parent”
android:layout_height=“fill_parent”>
<Button
android:layout_width=“fill_parent”
android:layout_height=“64px”
android:text=“Tool Bar”
android:layout_weight=“0”/>
<EditText
android:layout_width=“fill_parent”
android:layout_height=“fill_parent”
android:layout_weight=“1”/>
<Button
android:layout_width=“fill_parent”
android:layout_height=“64px”
android:text=“Menu Bar”
android:layout_weight=“0”/>
</LinearLayout>
[ weight3 ]
25/20
2. 리니어 레이아웃
 padding, margin
 여백과 관련된 속성
 padding
• 뷰와 내용물간의 간격 지정
• 뷰의 입장에서 볼 때 안쪽 여백을 뜻하며 뷰 자체의 속성
• 4면 모두 동일한 여백이 지정되며, paddingLeft, paddingTop, paddingRight, paddingBottom 으로 4
면의 개별 여백 지정 가능
 margin
• 뷰와 부모와의 간격을 지정하며, 근처에 형제 뷰가 있으면 동일한 간격으로 여백 생성
• 뷰의 입장에서 볼 때 바깥 여백을 뜻하며 레이아웃의 속성
• 4면 모두 동일한 여백이 지정되며, layout_marginLeft, layout_marginRight, layout_marginTop,
layout_marginBottom 으로 4면의 개별 여백 지정 가능
마진
패딩
Button
마진
패딩
26/20
2. 리니어 레이아웃
 padding, margin
Layout/padding1.xml
<?xml version=“1.0” encoding=“utf-8”>
<LinearLayout xmlns:android=http://schemas.android.com/apk/res/android
android:orientation=“vertical”
android:layout_width=“fill_parent”
android:layout_height=“fill_parent”>
<EditText
android:layout_width=“fill_parent”
android:layout_height=“wrap_content”
android:text=“Upper Text”/>
<LinearLayout
android:layout_width=“fill_parent”
android:layout_height=“wrap_content”
android:background=“#ff0000”>
<Button
android:layout_width=“fill_parent”
android:layout_height=“wrap_content”
android:text=“Button”/>
</LinearLayout>
<EditText
android:layout_width=“fill_parent”
android:layout_height=“wrap_content”
android:text=“Lower Text”/>
</LinearLayout>
Layout/padding2.xml
<LinearLayout
android:layout_width=“fill_parent”
android:layout_height=“wrap_content”
android:background=“#ff0000”
android:layout_margin=“10px”>
Layout/padding3.xml
<LinearLayout
android:layout_width=“fill_parent”
android:layout_height=“wrap_content”
android:background=“#ff0000”
android:layout_margin=“10px”
android:padding=“10px”>
[ padding2 ]
[ padding3 ]
[ padding1 ]
27/20
3. 다른 레이아웃
 RelativeLayout
 위젯과 부모와의 위치 관계 또는 위젯끼리의 관계를 지정함으로써 뷰를 배치
 위젯끼리의 관계 지정을 위하여 기준이 되는 위젯에 id를 반드시 지정해야 한다.
 리소스 컴파일러는 빠른 배치를 위해 위젯간의 관계를 한번에(one pass) 읽으며, 특정 뷰
가 다른 뷰의 위치에 종속적일 때 기준이 되는 뷰를 먼저 정의해야 한다.
ex: A를 B의 위에 배치하고 싶다면 XML 문서상에 B를 먼저 기술한 후 A를 나중에 기술해야 한다.
A
B
[ 원하는 배치 ]
<RelativeLayout>
<B
android:id=“@+id/b”
/>
<A
layout_above=“@id/b”
/>
</RelativeLayout>
[ XML 문서 ]
28/20
3. 다른 레이아웃
Layout/relative1.xml
 RelativeLayout
[ relative1 예제 실행 결과]
 레이아웃이 배치되는 순서
철수
철수
영희
<?xml version=“1.0” encoding=“utf-8”>
<RelativeLayout xmlns:android=http://schemas.android.com/apk/res/android
android:orientation=“vertical”
android:layout_width=“fill_parent”
android:layout_height=“wrap_content”>
<TextView
android:id=“@+id/chulsoo”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_marginRight=“20px”
android:textSize=“15pt”
android:text=“철수”/>
<TextView
android:id=“@+id/younghee”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_toRightOf=“@id/chulsoo”
android:textSize=“15pt”
android:text=“영희”/>
<TextView
android:id=“@+id/mongryong”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_below=“@id/younghee”
android:alignParentRight=“true”
android:layout_marginLeft=“10px”
android:textSize=“15pt”
android:text=“몽룡”/>
<TextView
android:id=“@+id/chunhyang”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_toRightOf=“@id/mongryong”
android:layout_alignBottom=“@id/mongryong”
android:textSize=“15pt”
android:text=“춘향”/>
</RelativeLayout>
철수
영희
몽룡
좌상단에
철수 오른쪽에
영희 밑에
부모의 오른쪽에
철수
영희
춘향 몽룡
몽룡 왼쪽에
몽룡의 아래쪽 정렬
29/20
3. 다른 레이아웃
 RelativeLayout
 RelativeLayout 예제 – name card
• 좌상단의 이미지를 제일 먼저 배치, 그 아래 삭제 버튼을 배치한다.
• 부모의 위쪽 변에 이름을 붙이면서 동시에 이미지의 오른쪽에 배치한다.
• 부모의 오른쪽에 전화번호를 붙이되 이름과 베이스를 맞추어 가지런히 한다.
• 설명 문자열은 이름 밑에 붙이되 왼쪽 변을 이름과 나란히 맞춘다.
[ 정상적인 결과 ]
[ 베이스를 맞추지 않은 결과 ]
 RelativeLayout 예제 – ListIconText
• 아이콘, 텍스트, 버튼 세 개로 구성된 항목 뷰를 리스트
뷰 안에 배치한 것.
• 아이콘은 왼쪽, 버튼은 오른쪽, 사이에 텍스트 배치
• 텍스트의 길이에 상관없이 버튼은 항상 항목 뷰의 오른
쪽에 정렬
[ ListIconText ]
30/20
3. 다른 레이아웃
 AbsoluteLayout
 관계나 순서에 상관없이 지정한 절대 좌표에 차일드 뷰를 배치한다.
 공식 문서에는 사용을 금지하였으며, RelativeLayout, FreamLayout을 사용한다.
Layout/absolute.xml
<?xml version=“1.0” encoding=“utf-8”>
<AbsoluteLayout xmlns:android=http://schemas.android.com/apk/res/android
android:layout_width=“fill_parent”
android:layout_height=“fill_parent”>
<TextView
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_x=“50px”
android:layout_y=“100px”
android:textSize=“15pt”
android:text=“(50,100)”/>
<TextView
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_x=“200px”
android:layout_y=“70px”
android:textSize=“15pt”
android:text=“(200,70)”/>
</AbsoluteLayout>
31/20
3. 다른 레이아웃
 FrameLayout
 차일드를 배치하는 규칙 없이 모든 차일드는 프레임의 좌상단에 나타나며, 차일드가 두
개 이상일 때는 추가된 순서대로 겹쳐서 표시된다.
• ViewGroup의 서브 클래스로 addView, removeView 등의 메서드로 실행 중에 차일드를 추가, 삭제
할 수 있으며, getChildCount 메서드로 차일드의 개수를 조사할 수 있다.
• 필요한 차일드만 표시하고 겹쳐진 차일드는 숨겨둘 수 있다.
• 차일드의 보임 상태는 개별 뷰의 visibility 속성을 사용하여 조정하며 실행 중에도 조건에 따라 뷰
의 보임 상태를 변경할 수 있다.
 속성
• foreground
- 차일드의 위쪽에 살짝 얹히는 이미지를 지정한다.
- 반투명한 색상, 이미지 사용이 가능하다.
• foregroundGravity
- 전경의 이미지를 배치할 방법을 지정하며, 디폴트는 fill이다.
• measureAllChildren
- 모든 차일드의 크기를 다 측정할 것인지, 보이거나 숨겨진 차일드의 크기만 적용할 것인지를 지정한다.
- 디폴트는 false여서 GONE 상태의 차일드 크기는 측정하지 않는다.
32/20
3. 다른 레이아웃
 FrameLayout
Layout/frame.xml
<?xml version=“1.0” encoding=“utf-8”>
<FrameLayout xmlns:android=http://schemas.android.com/apk/res/android
android:layout_width=“fill_parent”
android:layout_height=“fill_parent”>
<Button
android:id=“@+id/btn”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:text=“Push Button”/>
<ImabeView
android:id=“@+id/img”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:src=“@drawable/pride”/>
</FrameLayout>
Layout/frame.java
package exam.Layout;
import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;
public class Frame extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceSatae);
setContentView(R.layout.frame);
Button btn = (Button)findViewById(R.id.btn);
btn.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
ImageView img=(ImageView)findViewById(R.id.img);
if(img.getVisibility() == View.VISIBLE) {
img.setVisibility(View.INVISIBLE);
} else {
img.setVisibility(View.VISIBLE);
}
}
});
}
}
33/20
3. 다른 레이아웃
 TableLayout
 표 형식으로 차일드를 배치하는 레이아웃으로 바둑판 모양이다.
 테이블은 임의 개수 TableRow 객체로 구성되며, TableRow 안에 임의 개수 열이 배치되
고, 이를 셀이라 부르며 셀에는 차일드 뷰 하나가 들어간다.
 테이블의 전체 크기는 행(TableRow)*열(셀)이 된다.
 테이블의 차일드들은 정해진 규칙에 따라 크기가 결정되므로 크기 속성에 대한 제약이
있다.
• TableRow 객체의 높이는 항상 wrap_content로 강제됨.
: 여러 개의 행이 한 테이블에 공존해야 하기 때문이다.
• layout_width 속성은 따로 지정할 수 없으며 항상 fill_parent로 가정됨.
: 셀에 배치되는 자식 뷰는 무조건 주어진 셀 안에 배치되기 때문이다.
[ TableLayout 예제 ]
[ TableLayout 예제 ]
34/20
4. 레이아웃 관리
 레이아웃 중첩
 레이아웃은 뷰의 컨테이너이므로 View로부터 파생된 모든 객체를 레이아웃 안에 놓을
수 있으며, 레이아웃 자체도 View의 파생 클래스이므로 레이아웃끼리 중첩시킬 수 있다
.
 레이아웃 중첩 예제 – NestLayout
• 제일 바깥에 LinearLayout, 전체는 수직으로 뷰가 배열된다.
• 수직 LinearLayout 안에 TextView, Table, 수평 LinearLayout 이 일차 차일드로 배치된다.
• Table은 다시 2행 3열의 셀로 분할되고, 각 셀에는 텍스트 뷰가 들어있다.
• 수평 LinearLayout 안에는 세 개의 TextView가 배치되어 있다.
수직 리니어
TextView
테이블
TextView
TextView
TextView
TextView
TextView
TextView
TextView
TextView
TextView
테이블 로우
수평 리니어
35/20
4. 레이아웃 관리
 레이아웃 중첩
 레이아웃 중첩 예제 – MultPage
• 각 버튼을 누를 때 프레임 내의 모든 페이지를 일단 숨긴 후 버튼에 대응되는 페이지 하나만 표시
[ Page 1 button ]
[ Page 2 button ]
[ Page 3 button ]
36/20
4. 레이아웃 관리
 실행 중 속성 변경
 대부분의 속성은 실행 중 변경 가능하도록 메서드를 제공한다.
 속성값을 변경하는 메서드의 이름은 속성 이름 앞에 set이 붙고 속성의 첫 글자는 대문
자로 시작하며, 인수로 전달할 값은 수평일 때 0, 수직일 때 1이다.
 LinearLayout 클래스
public void LinearLayout.setOrientation(int orientation)
 gravity 변경 메서드
public void TextView.setGravity(int gravity)
 TextView 속성 관련 메서드
void setText(CharSequence text)
void setTextColor(int color)
void setTextSize(float size)
37/20
4. 레이아웃 관리
 실행 중 속성 변경
 메서드를 호출하기 전에 속성 변경의 대상이 되는 뷰를 찾는다
 이 메서드는 액티비티와 뷰에 정의되어 거의 모든 위치에서 호출이 가능하다.
 호출 객체에 따라 달리 사용되며, 액티비티에서 호출 시 전체 레이아웃에서 검색, 특정
뷰에서 검색 시 뷰의 차일드 중 하나를 검색한다.
• View Activity.findViewById (int id)
• View View.findViewById (int id)
 ID로부터(ById) 대응되는 뷰 객체(View)를 찾는다(find).
 id 인수로 검색 대상 뷰에 지정해 놓은 ID를 전달한다.
38/20
4. 레이아웃 관리
 레이아웃 전개
 XML 문서에 있는 레이아웃은 aapt 툴에 의해 이진 형태로 컴파일되어 실행 파일에 내
장된다.
 전개 (Inflation)
• XML 문서에 정의된 레이아웃과 속성을 읽어 실제 뷰 객체를 생성하는 동작
• setContentView : XML 문서의 리소스 ID를 전달받아 객체를 생성하여 액티비티를 채움
• 사용자가 직접 전개할 수 있으며, 안드로이드는 전개를 위해 시스템 수준에서 전개자를 따로 제공
한다.
- View inflate (int resource, ViewGroup root)
• LayoutInflater 클래스의 정적 메서드로 전개자를 구할 수 있다.
- 컨텍스트를 인수로 전달하여 전개자를 구하고, 이 전개자의 inflate 메서드를 호출한다.
- static LayoutInflater LayouotInflater.from (Context context)
• View의 정적 메서드를 이용하여 전개할 수 있다.
- static View inflate (Context context, int resource, ViewGroup root)
39/20
4. 레이아웃 관리
 레이아웃 파라미터
 일반 속성
• 뷰 외부와는 전혀 상관없이 뷰 자체의 속성을 지정한다.
• 주로 의미를 이해할 수 있도록 직관적인 이름을 사용한다.
• 위젯에 따라 적용 가능한 종류가 변경된다.
 레이아웃 파라미터
• 뷰가 배치되는 부모, 즉 레이아웃에 소속되는 속성, 부모에게 차일드 뷰를 배치할 방법을 지시한
다.
• 뷰 자체의 성질을 규정하는 것이 아니라 뷰 외부와의 관계를 지정한다.
• 레이아웃 파라미터의 이름은 “layout_”으로 시작된다.
• 위젯이 아닌 소속된 부모 레이아웃에 따라 적용 가능한 종류가 변경된다.
레이아웃
파라미터
ViewGroup.LayoutParams
layout_width, layout_height
ViewGroup.MarginLayoutParams
layout_marginLeft, layout_marginRight
LinearLayout.LayoutParams
layout_gravity, layout_weight
AbsoluteLayout.LayoutParams
layout_x, layout_y
RelativeLayout.LayoutParams
layout_above, layout_alignParentRight
[ 각 레이아웃 별로 제공되는 레이아웃 파라미터]
40/20
4. 레이아웃 관리
 레이아웃 파라미터
 레이아웃 파라미터 예제 – layoutparmeter, marginparameter
Layout/layoutparameter.xml
<?xml version=“1.0” encoding=“utf-8”>
<LinearLayout xmlns:android=http://schemas.android.com/apk/res/android
android:orientation=“vertical”
android:layout_width=“fill_parent”
android:layout_height=“fill_parent”
android:background=“#ffffff”
android:gravity=“center”>
<TextView
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:textColor=“#ff0000”
android:textSize=“20px”
android:text=“TextVieiw”
android:background=“#00ff00”/>
</LinearLayout>
Layout/layoutparameter.xml
<?xml version=“1.0” encoding=“utf-8”>
<LinearLayout xmlns:android=http://schemas.android.com/apk/res/android
android:orientation=“vertical”
android:layout_width=“fill_parent”
android:layout_height=“fill_parent”
android:background=“#ffffff”>
<Button
android:layout_width=“wrap_content”
android:layout_height=“fill_parent”
android:text=“Button With Margin”
android:layout_marginTop=“30px”
android:layout_marginBottom=“30px”/>
</LinearLayout>
[ layoutparameter 예제 ]
[ marginparameter 예제 ]
41/20
안드로이드 프로그래밍 정복(Android Programming Complete
Guide)