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

Thêm Button vào Layout theo dòng theo chương trình bằng Kotlin

Hướng dẫn này minh họa cách thêm Button vào Layout theo từng dòng một cách lập trình trong Android sử dụng Kotlin.

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

Mở Android Studio, chọn File → New Project và điền đầy đủ thông tin cần thiết.

Bước 2: Thiết kế giao diện cơ bản (activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:orientation="vertical"
    tools:context=".MainActivity">
</LinearLayout>

Bước 3: Viết code MainActivity.kt

import android.os.Bundle
import android.view.Gravity
import android.widget.Button
import android.widget.LinearLayout
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"

        val layout = LinearLayout(this)
        layout.orientation = LinearLayout.VERTICAL

        for (i in 0..2) {
            val row = LinearLayout(this)
            row.layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            )
            row.gravity = Gravity.CENTER

            for (j in 0..3) {
                val btnTag = Button(this)
                btnTag.layoutParams = LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.MATCH_PARENT
                )
                btnTag.text = "Button ${j + 1 + i * 4}"
                btnTag.id = j + 1 + i * 4
                row.addView(btnTag)
            }
            layout.addView(row)
        }
        setContentView(layout)
    }
}

Bước 4: Cấu hình AndroidManifest.xml

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

    <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

Kết nối thiết bị Android thực, nhấn Run trong Android Studio. Ứng dụng sẽ hiển thị lưới 3 hàng x 4 cột các Button được tạo động bằng code.