Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách làm GridLayout vừa màn hình (fit screen) trên Android bằng Kotlin

Giới thiệu

Ví dụ minh họa cách tạo GridLayout động bằng code Kotlin, tính toán số hàng/cột để lưới vừa khít màn hình, thêm các ImageView vào mỗi ô. Cách này cho phép kiểm soát hoàn toàn layout tại runtime.

Các bước thực hiện

Bước 1: Tạo dự án mới

Android Studio > File > New Project.

Bước 2: Layout (activity_main.xml) - GridLayout gốc

<?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">

    <!-- Các Button mẫu, sẽ bị xóa và thay thế bằng code -->
    <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>

Bước 3: MainActivity.kt - Tạo Grid động

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(R.id.tableGrid)
        gridLayout.removeAllViews() // Xóa Button mẫu trong XML

        val totalItems = 12
        val columnCount = 5
        val rowCount = totalItems / columnCount + (if (totalItems % columnCount > 0) 1 else 0)

        gridLayout.columnCount = columnCount
        gridLayout.rowCount = rowCount

        var index = 0
        var col = 0
        var row = 0

        while (index < totalItems) {
            if (col == columnCount) {
                col = 0
                row++
            }

            val imageView = ImageView(this)
            imageView.setImageResource(R.drawable.ic_launcher_background) // Drawable mẫu

            val params = GridLayout.LayoutParams().apply {
                height = TableLayout.LayoutParams.WRAP_CONTENT
                width = TableLayout.LayoutParams.WRAP_CONTENT
                rightMargin = 5
                topMargin = 5
                setGravity(Gravity.CENTER)
                columnSpec = GridLayout.spec(col)
                rowSpec = GridLayout.spec(row)
            }

            imageView.layoutParams = params
            gridLayout.addView(imageView)

            index++
            col++
        }
    }
}

Bước 4: AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.gridlayoutfit">

    <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>

Chạy ứng dụng

Chạy app, GridLayout sẽ hiển thị 12 ImageView xếp thành 5 cột, 3 hàng (hàng cuối 2 item), căn giữa màn hình, có margin 5dp.

Cách hiện đại & Tốt hơn: RecyclerView + GridLayoutManager

GridLayout ít được dùng cho danh sách động vì:

  • Không hỗ trợ recycling view (tốn bộ nhớ với list lớn).
  • Không có scroll tích hợp (cần bọc trong ScrollView).
  • Khó xử lý click, animation, item decoration.

RecyclerView với GridLayoutManager là tiêu chuẩn hiện nay:

1. Layout (activity_main.xml)

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/recyclerView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="8dp"
    tools:listitem="@layout/item_grid_image" />

2. Item Layout (res/layout/item_grid_image.xml)

<ImageView xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/imageView"
    android:layout_width="match_parent"
    android:layout_height="120dp"
    android:scaleType="centerCrop"
    android:src="@drawable/ic_launcher_background" />

3. Adapter

class GridAdapter(private val items: List) : RecyclerView.Adapter() {
    inner class VH(view: View) : RecyclerView.ViewHolder(view) {
        val img: ImageView = view.findViewById(R.id.imageView)
    }
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
        VH(LayoutInflater.from(parent.context).inflate(R.layout.item_grid_image, parent, false))
    override fun onBindViewHolder(holder: VH, position: Int) {
        holder.img.setImageResource(items[position])
    }
    override fun getItemCount() = items.size
}

4. Activity

val recyclerView = findViewById(R.id.recyclerView)
recyclerView.layoutManager = GridLayoutManager(this, 5) // 5 cột
recyclerView.adapter = GridAdapter(listOf(
    R.drawable.img1, R.drawable.img2, R.drawable.img3, R.drawable.img4,
    R.drawable.img5, R.drawable.img6, R.drawable.img7, R.drawable.img8,
    R.drawable.img9, R.drawable.img10, R.drawable.img11, R.drawable.img12
))
recyclerView.addItemDecoration(GridSpacingItemDecoration(5, 5, true)) // Margin item

Tự động tính số cột vừa màn hình (Auto-fit)

Dùng GridLayoutManager với spanSizeLookup hoặc thư viện FlexboxLayout / FlowLayout. Hoặc tự tính:

fun calculateSpanCount(context: Context, itemWidthDp: Int): Int {
    val screenWidthPx = resources.displayMetrics.widthPixels
    val itemWidthPx = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, itemWidthDp.toFloat(), resources.displayMetrics)
    return max(1, (screenWidthPx / itemWidthPx).toInt())
}
// Sử dụng:
val spanCount = calculateSpanCount(this, 100) // Mỗi item ~100dp
recyclerView.layoutManager = GridLayoutManager(this, spanCount)