ภาพรวม
ตัวอย่างนี้สาธิตวิธีการทำให้ GridLayout ปรับขนาดและจัดวางรายการให้พอดีกับหน้าจอใน Android โดยใช้ Kotlin สร้าง Grid แบบไดนามิก
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
สร้างโปรเจกต์ Android ใหม่ใน Android Studio
ขั้นตอนที่ 2: จัดรูปแบบหน้าจอหลัก (activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:id="@+id/tableGrid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
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.kt
สร้าง Grid แบบไดนามิกด้วย ImageView คำนวณแถว/คอลัมน์อัตโนมัติ:
import android.os.Bundle
import android.view.Gravity
import android.widget.GridLayout
import android.widget.ImageView
import android.widget.TableLayout
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
val gridLayout = findViewById<GridLayout>(R.id.tableGrid)
gridLayout.removeAllViews() // ลบ View เดิมใน XML
val total = 12 // จำนวนรายการทั้งหมด
val column = 5 // จำนวนคอลัมน์ที่ต้องการ
val row = total / column
gridLayout.columnCount = column
gridLayout.rowCount = row + 1
var i = 0
var c = 0
var r = 0
while (i < total) {
if (c == column) {
c = 0
r++
}
val imageView = ImageView(this).apply {
setImageResource(R.drawable.ic_launcher_background)
val param = GridLayout.LayoutParams().apply {
height = TableLayout.LayoutParams.WRAP_CONTENT
width = TableLayout.LayoutParams.WRAP_CONTENT
rightMargin = 5
topMargin = 5
setGravity(Gravity.CENTER)
columnSpec = GridLayout.spec(c)
rowSpec = GridLayout.spec(r)
}
layoutParams = param
}
gridLayout.addView(imageView)
i++
c++
}
}
}
ขั้นตอนที่ 4: ตั้งค่า AndroidManifest.xml
ใช้การตั้งค่ามาตรฐาน
ทดสอบการทำงาน
รันแอป จะแสดง Grid 5 คอลัมน์ 3 แถว (12 รายการ) จัดอยู่กึ่งกลางหน้าจอ
ข้อมูลเพิ่มเติม
- GridLayout vs RecyclerView: GridLayout ใช้สำหรับ Layout คงที่/เรียบง่าย RecyclerView + GridLayoutManager ใช้สำหรับรายการเยอะ ต้องการ Recycling/Scrolling
- FlexboxLayout: Google FlexboxLayout รองรับ Wrap แบบยืดหยุ่นกว่า (คล้าย CSS Flexbox)
- ConstraintLayout: สร้าง Grid ได้ด้วย ConstraintSet และ Guideline/Barrier
- Percent Support: ใช้ `layout_width="0dp"` + `app:layout_constraintWidth_percent="0.2"` สำหรับ 20% ความกว้าง