ตัวอย่างนี้สาธิตวิธี เปลี่ยน LayoutParams (Width/Height/Weight) ของ View แบบ Runtime โดยเฉพาะ TextView/Button ภายใน LinearLayout
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
Android Studio → New Project → Empty Activity
ขั้นตอนที่ 2: Layout (activity_main.xml)
ใช้ LinearLayout เพื่อให้ Weight ทำงาน
<?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="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:padding="24dp"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="24dp"
android:text="Layout Weight Demo"
android:textColor="@android:color/holo_green_dark"
android:textSize="24sp"
android:textStyle="bold" />
<Button
android:id="@+id/btnChangeWeight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0"
android:text="Expand Me (Weight=0)"
android:textSize="18sp"
android:textStyle="bold" />
</LinearLayout>
ขั้นตอนที่ 3: โค้ดหลัก (MainActivity.kt)
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.LinearLayout
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
private var isExpanded = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "Layout Weight Demo"
val btn = findViewById
🔑 จุดสำคัญ: LayoutParams ต้องตรงกับ Parent
| Parent Layout | LayoutParams Class | Weight Property |
|---|---|---|
| LinearLayout | LinearLayout.LayoutParams | weight (Float) |
| ConstraintLayout | ConstraintLayout.LayoutParams | ใช้ horizontalWeight, verticalWeight |
| RelativeLayout | RelativeLayout.LayoutParams | ไม่รองรับ Weight |
| FrameLayout | FrameLayout.LayoutParams | ไม่รองรับ Weight |
💡 ตัวอย่าง: แบ่งพื้นที่ 2:1 ระหว่าง 2 ปุ่ม
val btn1 = findViewById
ขั้นตอนที่ 4: AndroidManifest.xml
Manifest มาตรฐาน
ทดสอบ
- รันแอป → ปุ่มกว้างพอดีข้อความ (Weight=0)
- กดปุ่ม → ขยายเต็มหน้าจอ (Weight=1, Width=0)
- กดอีกครั้ง → กลับสู่ขนาดเดิม
⚠️ ข้อผิดพลาดที่พบบ่อย
- ❌ Cast LayoutParams ผิด Parent (เช่น RelativeLayout.LayoutParams ใน LinearLayout) → ClassCastException
- ❌ ตั้ง Width = WRAP_CONTENT พร้อม Weight > 0 → Weight จะไม่ทำงาน (ต้อง Width = 0)
- ❌ ลืม
button.layoutParams = paramsหลังแก้ไข