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

วิธีเพิ่ม Button แบบ Dynamic ใน Android

ภาพรวม

ตัวอย่างนี้สาธิตการสร้างและเพิ่ม Button เข้าไปใน Layout โดยโปรแกรม (Programmatically) ระหว่าง Runtime

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

เปิด Android Studio → File → New Project และกรอกข้อมูลที่จำเป็น

ขั้นตอนที่ 2: เลย์เอาต์ (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:id="@+id/relativeLayout"
    android:gravity="center"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
</RelativeLayout>

ขั้นตอนที่ 3: โค้ดหลัก (src/MainActivity.java)

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    RelativeLayout relativeLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        relativeLayout = findViewById(R.id.relativeLayout);

        // สร้าง Button ใหม่
        Button button = new Button(this);
        button.setText("Dynamically created Button");
        
        // ตั้งค่า LayoutParams ตาม Parent (RelativeLayout)
        button.setLayoutParams(new RelativeLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        ));

        // เพิ่ม Event Listener
        button.setOnClickListener(v -> 
            Toast.makeText(MainActivity.this, 
                "This button is created dynamically", 
                Toast.LENGTH_SHORT).show()
        );

        // เพิ่มเข้า Layout
        if (relativeLayout != null) {
            relativeLayout.addView(button);
        }
    }
}

ขั้นตอนที่ 4: AndroidManifest.xml

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

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

การทดสอบ

รันแอป จะเห็น Button ปรากฏขึ้นตรงกลางหน้าจอ กดแล้วแสดง Toast

วิธีเพิ่ม Button แบบ Dynamic ใน Android

เทคนิคการเพิ่ม View แบบ Dynamic

1. LayoutParams ต้องตรงกับ Parent

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

2. ตั้งค่า Position ใน RelativeLayout

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
    ViewGroup.LayoutParams.WRAP_CONTENT,
    ViewGroup.LayoutParams.WRAP_CONTENT
);
params.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
// หรือ
params.addRule(RelativeLayout.BELOW, R.id.someView);
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
params.setMargins(left, top, right, bottom);

button.setLayoutParams(params);

3. เพิ่มหลาย View พร้อมกัน

for (int i = 0; i < 5; i++) {
    Button btn = new Button(this);
    btn.setText("Button " + (i + 1));
    btn.setId(View.generateViewId()); // API 17+ สำหรับ ID เฉพาะ
    linearLayout.addView(btn);
}

4. ลบ View แบบ Dynamic

// ลบ View เฉพาะตัว
relativeLayout.removeView(button);

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

// ลบโดย Index
relativeLayout.removeViewAt(index);

5. ใช้กับ RecyclerView (แนะนำสำหรับรายการเยอะ)

สำหรับรายการที่มีหลายรายการ ควรใช้ RecyclerView + Adapter แทนการ addView โดยตรง เพื่อ Performance และ Memory Efficiency

⚠️ ข้อควรระวัง: การ addView จำนวนมากใน ScrollView/LinearLayout อาจทำให้ UI Lag ควรใช้ RecyclerView แทน