GridLayout은 행과 열로 구성된 테이블 화면을 만드는 레이아웃 클래스다.
LinearLayout처럼 orientation처럼 속성으로 가로나 세로 방향으로 뷰를 나열하는데, LinearLayout과 다르게 줄바꿈을 자동으로 해준다.
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:rowCount="3"
android:orientation="vertical">
<Button android:text="A" />
<Button android:text="B" />
<Button android:text="C" />
<Button android:text="D" />
<Button android:text="E" />
</GridLayout>
행의 개수를 3개로 설정하고, 세로로 배치하였다.
필요시 horizontal, columnCount로 설정할 수도 있다.
GridLayout으로 뷰를 배치하면 추가한 순서대로 배치된다.
layout_row, layout_column 속성을 이용하면 특정 뷰의 위치를 조정할 수 있다.
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:columnCount="3">
<Button android:text="A" />
<Button android:text="B" />
<Button
android:layout_row="1"
android:layout_column="1"
android:text="C" />
<Button android:text="D" />
<Button android:text="E" />
</GridLayout>
android:layout_row="1"
: 이는 버튼 C를 두 번째 행(인덱스로는 1)에 위치시킨다. android:layout_column="1"
: 이는 버튼 C를 두 번째 열(인덱스로는 1)에 위치시킨다.헷갈림 주의) C를 해당 열의 1번째 인덱스(즉, 0번째가 아닌 1번째), 해당 열의 1번째 인덱스(즉, 0번째가 아닌 1번째)에 위치하는 것이 아니라, 그냥 1번째 행과 열에 위치시키는 것이다.
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnCount="3"
android:orientation="horizontal">
<Button android:text="A" />
<Button android:text="HELLOWORLD HELLOWORLD" />
<Button android:text="C" />
<Button android:text="D" />
<Button
android:layout_gravity="fill_horizontal"
android:text="E" />
<Button android:text="F" />
</GridLayout>
android:layout_gravity="fill_horizontal"
를 적용하면 된다.어떤 뷰가 테이블에서 여러 칸을 차지하게 설정할 수도 있다.
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnCount="3"
android:orientation="horizontal">
<Button
android:layout_rowSpan="2"
android:layout_columnSpan="2"
android:layout_gravity="fill"
android:text="A" />
<Button android:text="B" />
<Button android:text="C" />
<Button android:text="D" />
<Button android:text="E" />
<Button android:text="F" />
</GridLayout>
A 버튼에 layout_columnSpan과 layout_rowSpan을 모두 2로 설정했다.
그러면 가로로 2칸, 세로로 2칸을 병합하므로 A 버튼을 4칸을 차지한다.
TableLayout도 마찬가지로 뷰를 테이블 구조로 나타내는 레이아웃이다.
하지만 tableLayout은 불편해서 자주 사용하지는 않는다.
GridLayout
은 행과 열로 구성된 레이아웃이다.orientation
으로 방향을 설정한다.rowCount
로 세로 행 개수를 설정한다.columnCount
로 가로 열 개수를 설정한다.layout_row
로 뷰의 세로 위치를 설정한다.layout_column
로 뷰의 가로 위치를 설정한다.layout_gravity
속성으로 뷰의 크기를 확장할 수 있다.layout_columnSpan
으로 열을 병합한다.layout_rowSpan
으로 행을 병합한다.