이 튜토리얼에서는 안드로이드(Android)에서 GridLayout을 화면 크기에 맞게 배치하는 방법을 단계별로 알아봅니다. GridLayout은 UI 요소를 행과 열의 격자 형태로 배치할 수 있는 레이아웃으로, 계산기나 사진 갤러리처럼 균일한 그리드 화면을 만들 때 특히 유용합니다.
1단계: 새 프로젝트 생성
안드로이드 스튜디오(Android Studio)에서 File → New Project 메뉴로 이동해 새 프로젝트를 생성하고, 필요한 항목을 모두 입력하여 프로젝트 설정을 완료합니다.
2단계: 레이아웃 작성 (activity_main.xml)
res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. GridLayout 안에 16개의 버튼을 배치하는 기본 구조입니다.
<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tableGrid"
android:layout_gravity="center"
android:columnCount="4"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button android:text="1" />
<Button android:text="2" />
<Button android:text="3" />
<Button android:text="4" />
<Button android:text="5" />
<Button android:text="6" />
<Button android:text="7" />
<Button android:text="8" />
<Button android:text="9" />
<Button android:text="10" />
<Button android:text="11" />
<Button android:text="12" />
<Button android:text="13" />
<Button android:text="14" />
<Button android:text="15" />
<Button android:text="16" />
</GridLayout>
3단계: MainActivity.java 작성
src/MainActivity.java에 다음 코드를 추가합니다. 이 코드는 GridLayout의 열과 행 개수를 동적으로 계산해 지정하고, 반복문을 통해 ImageView를 생성해 각 그리드 셀에 배치합니다. 또한 셀 사이의 여백(margin)과 중앙 정렬(gravity)도 함께 설정합니다.
package com.app.sample;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.TableLayout;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridLayout gridLayout = (GridLayout)findViewById(R.id.tableGrid);
gridLayout.removeAllViews();
int total = 12;
int column = 5;
int row = total / column;
gridLayout.setColumnCount(column);
gridLayout.setRowCount(row + 1);
for(int i =0, c = 0, r = 0; i < total; i++, c++){
if(c == column){
c = 0;
r++;
}
ImageView oImageView = new ImageView(this);
oImageView.setImageResource(R.drawable.ic_launcher_background);
GridLayout.LayoutParams param =new GridLayout.LayoutParams();
param.height = TableLayout.LayoutParams.WRAP_CONTENT;
param.width = TableLayout.LayoutParams.WRAP_CONTENT;
param.rightMargin = 5;
param.topMargin = 5;
param.setGravity(Gravity.CENTER);
param.columnSpec = GridLayout.spec(c);
param.rowSpec = GridLayout.spec(r);
oImageView.setLayoutParams (param);
gridLayout.addView(oImageView);
}
}
}
4단계: 매니페스트 설정 (AndroidManifest.xml)
Manifests/AndroidManifest.xml 파일에 아래 코드를 추가합니다.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.app.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
앱 실행 및 결과 확인
이제 애플리케이션을 실행해 결과를 확인해 보겠습니다. 실제 안드로이드 기기가 컴퓨터에 연결되어 있다고 가정합니다. 안드로이드 스튜디오에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 Run 아이콘을 클릭하세요. 실행 대상 목록에서 자신의 모바일 기기를 선택하면, 기기 화면에 아래 이미지와 같은 기본 화면이 표시됩니다.

참고: 셀 크기를 화면에 맞게 늘리는 팁
위 예제에서는 각 셀이 내용물 크기(wrap_content)만큼만 표시됩니다. 셀을 화면 너비에 꽉 차게 배치하고 싶다면 LayoutParams의 columnSpec에 가중치(weight)를 지정하는 방법을 활용할 수 있습니다. 예를 들어 param.columnSpec = GridLayout.spec(c, 1f);처럼 작성하면 각 열이 남은 공간을 균등하게 나누어 가지며, 화면 크기가 달라져도 그리드가 자동으로 확장·축소됩니다. 이 방식을 응용하면 다양한 해상도의 기기에서 일관된 그리드 레이아웃을 구현할 수 있습니다.