Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีเพิ่ม TextView ลงใน LinearLayout แบบไดนามิกใน Android Kotlin

บทนำ

ตัวอย่างนี้สาธิตการสร้างและเพิ่ม View (TextView) เข้าไปใน LinearLayout โดยโปรแกรม (Programmatically) แทนการประกาศใน XML

ขั้นตอนที่ 1: สร้างโปรเจกต์

สร้างโปรเจกต์ Android ใหม่ใน Android Studio

ขั้นตอนที่ 2: Layout (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:id="@+id/linearLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp"
    tools:context=".MainActivity">
</LinearLayout>

ขั้นตอนที่ 3: MainActivity.kt

import android.graphics.Color
import android.os.Bundle
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity

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

        val linearLayout: LinearLayout = findViewById(R.id.linearLayout)

        // สร้าง TextView แบบไดนามิก
        val textView = TextView(this).apply {
            text = "I am added dynamically to the view"
            textSize = 24f
            setTextColor(Color.RED)
            gravity = android.view.Gravity.CENTER
            setPadding(16, 16, 16, 16)
        }

        // กำหนด LayoutParams
        val params = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        ).apply {
            margins = 16 // left, top, right, bottom (API 26+)
            // หรือใช้ setMargins สำหรับ API เก่า
        }
        textView.layoutParams = params

        // เพิ่มเข้า LinearLayout
        linearLayout.addView(textView)

        // เพิ่มอีกหลายตัว
        for (i in 1..5) {
            val dynamicText = TextView(this).apply {
                text = "Dynamic Item #$i"
                textSize = 18f
                setTextColor(Color.DKGRAY)
                gravity = android.view.Gravity.CENTER
                setPadding(16, 16, 16, 16)
            }
            linearLayout.addView(dynamicText)
        }
    }
}

ขั้นตอนที่ 4: Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.dynamicviews">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:layout="@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>

LayoutParams สำหรับ ViewGroup ต่างๆ

Parent ViewGroupLayoutParams Class
LinearLayoutLinearLayout.LayoutParams
RelativeLayoutRelativeLayout.LayoutParams
ConstraintLayoutConstraintLayout.LayoutParams
FrameLayoutFrameLayout.LayoutParams
GridLayoutGridLayout.LayoutParams
CoordinatorLayoutCoordinatorLayout.LayoutParams

LinearLayout.LayoutParams Properties

val params = LinearLayout.LayoutParams(
    width = LinearLayout.LayoutParams.MATCH_PARENT,
    height = LinearLayout.LayoutParams.WRAP_CONTENT
).apply {
    weight = 1f           // สำหรับ weight distribution
    gravity = Gravity.CENTER
    margins = 16          // API 26+: left, top, right, bottom
    // setMargins(left, top, right, bottom) // API เก่า
}

แนวทางทันสมัย: RecyclerView แทนการ Add View แบบ Manual

สำหรับรายการข้อมูลที่เยอะหรือเปลี่ยนแปลงบ่อย ควรใช้ RecyclerView + Adapter แทน:

  • ประสิทธิภาพดีกว่า (View Recycling)
  • จัดการ Memory ดีกว่า
  • รองรับ Animation, DiffUtil
  • แยก Logic การแสดงผลจาก Data

ตัวอย่างเพิ่ม View แบบมี Event Listener

val button = Button(this).apply {
    text = "Click Me #$count"
    setOnClickListener { v ->
        Toast.makeText(this@MainActivity, "Clicked: ${(v as Button).text}", Toast.LENGTH_SHORT).show()
    }
    layoutParams = LinearLayout.LayoutParams(
        LinearLayout.LayoutParams.WRAP_CONTENT,
        LinearLayout.LayoutParams.WRAP_CONTENT
    ).apply { gravity = Gravity.CENTER }
}
linearLayout.addView(button)

ลบ View แบบไดนามิก

// ลบ View เฉพาะตัว
linearLayout.removeView(textView)

// ลบทั้งหมด
linearLayout.removeAllViews()

// ลบตาม Index
linearLayout.removeViewAt(0)