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

วิธีเพิ่ม Custom View ใน Alert Dialog

ตัวอย่างนี้สาธิตวิธี เพิ่ม Custom View ใน Alert Dialog

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

ไปที่ File → New Project และกรอกรายละเอียดที่จำเป็นทั้งหมด

ขั้นตอนที่ 2: เพิ่มโค้ดใน res/layout/activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:gravity="center"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/click"
        android:layout_width="wrap_content"
        android:textSize="30sp"
        android:layout_height="wrap_content"
        android:text="Click" />
</LinearLayout>

ขั้นตอนที่ 3: เพิ่มโค้ดใน src/MainActivity.java

package com.example.myapplication;

import android.annotation.TargetApi;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    TextView text;

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        text = findViewById(R.id.click);
        text.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAlertDialog();
            }
        });
    }

    private void showAlertDialog() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
        // Inflate Custom Layout
        final View customLayout = getLayoutInflater().inflate(R.layout.custom, null);
        alertDialog.setView(customLayout);

        alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // ดึงข้อมูลจาก Custom View
                EditText editText = customLayout.findViewById(R.id.editText);
                Toast.makeText(MainActivity.this, editText.getText().toString(), Toast.LENGTH_LONG).show();
            }
        });

        AlertDialog alert = alertDialog.create();
        alert.setCanceledOnTouchOutside(false);
        alert.show();
    }
}

ขั้นตอนที่ 4: สร้าง Custom Layout (res/layout/custom.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="16dp">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Enter your name:"
        android:textSize="16sp"
        android:layout_marginBottom="8dp"/>
    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Name"
        android:inputType="text"/>
</LinearLayout>

การทดสอบแอปพลิเคชัน

รันแอปพลิเคชันบนอุปกรณ์ Android จริง ใน Android Studio คลิกไอคอน Run เลือกอุปกรณ์ แล้วตรวจสอบหน้าจอเริ่มต้น

วิธีเพิ่ม Custom View ใน Alert Dialog

คลิก TextView จะเปิด Alert Dialog พร้อม Custom View (EditText)

วิธีเพิ่ม Custom View ใน Alert Dialog

กรอกข้อมูล คลิก OK จะแสดง Toast

วิธีเพิ่ม Custom View ใน Alert Dialog

จุดสำคัญของ Custom View Dialog

  • alertDialog.setView(View) - ตั้งค่า Custom View (แทนที่ Title/Message/List)
  • getLayoutInflater().inflate(R.layout.custom, null) - Inflate Layout XML เป็น View
  • เข้าถึง View ภายใน Custom Layout ผ่าน customLayout.findViewById()
  • Custom View สามารถเป็น Layout ใดก็ได้ (Form, List, Image, Video, Map, etc.)

รูปแบบ Dialog แบบเต็ม (Full-Featured)

AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.CustomDialogTheme);
View dialogView = getLayoutInflater().inflate(R.layout.dialog_custom, null);

// Setup Views
EditText input = dialogView.findViewById(R.id.input);
Button btnCancel = dialogView.findViewById(R.id.btnCancel);
Button btnConfirm = dialogView.findViewById(R.id.btnConfirm);

builder.setView(dialogView);
AlertDialog dialog = builder.create();

btnCancel.setOnClickListener(v -> dialog.dismiss());
btnConfirm.setOnClickListener(v -> {
    String text = input.getText().toString();
    // Do something
    dialog.dismiss();
});

dialog.show();

คำแนะนำ: ใช้ DialogFragment แทน (Best Practice)

  • จัดการ Lifecycle อัตโนมัติ (Rotation, Background)
  • รองรับ Back Stack
  • โค้ดแยกต่างหาก ดูแลรักษาง่าย
  • ใช้ DialogFragment + onCreateDialog() หรือ onCreateView()