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

วิธีแสดง Alert Dialog ใน Android


Alert Dialog คืออะไร?

Alert Dialog เป็นกล่องโต้ตอบ (Popup) ที่แสดงข้อความและให้ผู้ใช้เลือกการกระทำ เช่น ยืนยัน (OK) หรือยกเลิก (Cancel) ใช้สำหรับการยืนยันการลบข้อมูล ออกจากแอป หรือการกระทำสำคัญอื่นๆ

เมธอดหลักของ AlertDialog.Builder

เมธอดคำอธิบาย
setTitle(CharSequence)ตั้งค่าหัวข้อ Dialog
setMessage(CharSequence)ตั้งค่าข้อความเนื้อหา
setIcon(int resId)ตั้งค่าไอคอน
setPositiveButton(CharSequence, OnClickListener)ปุ่มบวก (ปกติคือ OK/Yes)
setNegativeButton(CharSequence, OnClickListener)ปุ่มลบ (ปกติคือ Cancel/No)
setNeutralButton(CharSequence, OnClickListener)ปุ่มกลาง (เช่น Later)
setView(View)ตั้งค่า Custom Layout
setCancelable(boolean)กด Back/คลิกนอกเพื่อปิดได้หรือไม่
create()สร้าง AlertDialog object
show()แสดง Dialog

ตัวอย่างพื้นฐาน: Alert Dialog แบบมี 2 ปุ่ม

Layout (activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/btnShowDialog"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="แสดง Alert Dialog"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

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

        Button btnShowDialog = findViewById(R.id.btnShowDialog);
        btnShowDialog.setOnClickListener(v -> showAlertDialog());
    }

    private void showAlertDialog() {
        new AlertDialog.Builder(this)
            .setTitle("ยืนยันการลบ")
            .setMessage("คุณต้องการลบรายการนี้ใช่หรือไม่?")
            .setIcon(android.R.drawable.ic_dialog_alert)
            .setPositiveButton("ใช่", (dialog, which) -> {
                Toast.makeText(this, "ลบรายการแล้ว", Toast.LENGTH_SHORT).show();
                // ทำการลบข้อมูลที่นี่
            })
            .setNegativeButton("ยกเลิก", (dialog, which) -> {
                Toast.makeText(this, "ยกเลิกการลบ", Toast.LENGTH_SHORT).show();
                dialog.dismiss();
            })
            .setCancelable(false) // ไม่ให้ปิดได้โดยการกด Back
            .show();
    }
}

ตัวอย่างขั้นสูง: Custom Layout Dialog

เมื่อต้องการ UI ที่ซับซ้อน เช่น Form ล็อกอิน เลือกวันที่ ฯลฯ

สร้าง Layout แยก (dialog_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="24dp">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="เข้าสู่ระบบ"
        android:textSize="20sp"
        android:textStyle="bold"
        android:gravity="center"
        android:layout_marginBottom="16dp"/>

    <EditText
        android:id="@+id/etEmail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="อีเมล"
        android:inputType="textEmailAddress"
        android:layout_marginBottom="12dp"/>

    <EditText
        android:id="@+id/etPassword"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="รหัสผ่าน"
        android:inputType="textPassword"/>

</LinearLayout>

แสดง Custom Dialog

private void showCustomDialog() {
    View dialogView = getLayoutInflater().inflate(R.layout.dialog_custom, null);
    EditText etEmail = dialogView.findViewById(R.id.etEmail);
    EditText etPassword = dialogView.findViewById(R.id.etPassword);

    new AlertDialog.Builder(this)
        .setView(dialogView)
        .setPositiveButton("เข้าสู่ระบบ", (dialog, which) -> {
            String email = etEmail.getText().toString().trim();
            String password = etPassword.getText().toString().trim();
            // ตรวจสอบและ login
        })
        .setNegativeButton("ยกเลิก", null)
        .show();
}

แนวทางปฏิบัติที่ดี (Best Practices)

  • ใช้ MaterialAlertDialogBuilder: จาก Material Components Library เพื่อให้รองรับ Material Design 3
  • หลีกเลี่ยง Memory Leak: ใช้ `requireContext()` หรือ `requireActivity()` ใน Fragment
  • จัดการ Lifecycle: Dialog อาจถูก dismiss เมื่อ Configuration Change ใช้ DialogFragment แทนสำหรับ Dialog ที่ซับซ้อน
  • Accessibility: ตั้งค่า contentDescription ให้กับ Icon และปุ่ม

Migration ไป Material 3

// build.gradle
implementation 'com.google.android.material:material:1.12.0'

// ในโค้ด
import com.google.android.material.dialog.MaterialAlertDialogBuilder;

new MaterialAlertDialogBuilder(this, R.style.ThemeOverlay_Material3_MaterialAlertDialog)
    .setTitle("Title")
    .setMessage("Message")
    .setPositiveButton("OK", null)
    .show();