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

วิธีสร้าง Custom Alert Dialog ใน Android

ภาพรวม

ตัวอย่างนี้สาธิตการสร้าง AlertDialog แบบกำหนดเอง (Custom Layout) พร้อมรูปภาพ ข้อความ และปุ่ม ด้วยการ Inflater Layout XML แยกต่างหาก

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

Android Studio → File → New Project → Empty Activity

ขั้นตอนที่ 2: จัดรูปแบบหน้าจอหลัก (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/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@id/buttonShowCustomDialog"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="86dp"
        android:gravity="center"
        android:text="CLICK TO VIEW CUSTOM ALERT DIALOG"
        android:textSize="18sp"
        android:textStyle="bold" />

    <Button
        android:id="@+id/buttonShowCustomDialog"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="131dp"
        android:onClick="showCustomDialog"
        android:text="Click"
        android:textStyle="bold"
        style="@android:style/Widget.DeviceDefault.Button.Inset" />

</RelativeLayout>

ขั้นตอนที่ 3: สร้าง Custom Dialog Layout (custom_dialog.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="24dp"
    android:gravity="center">

    <ImageView
        android:id="@+id/image"
        android:layout_width="64dp"
        android:layout_height="64dp"
        android:src="@drawable/ic_alert"
        android:contentDescription="Alert Icon"
        app:tint="?attr/colorError" />

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="Alert...!"
        android:textSize="20sp"
        android:textStyle="bold"
        android:textColor="?attr/colorOnSurface" />

    <TextView
        android:id="@+id/message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="This is a custom alert dialog with custom layout."
        android:textSize="16sp"
        android:textColor="?attr/colorOnSurfaceVariant"
        android:gravity="center" />

    <Button
        android:id="@+id/dialogButtonOK"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:text="Dismiss"
        style="@style/Widget.MaterialComponents.Button.OutlinedButton" />

</LinearLayout>

ขั้นตอนที่ 4: เขียนโค้ด MainActivity.java

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private Button button;

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

        button = findViewById(R.id.buttonShowCustomDialog);
        button.setOnClickListener(v -> showCustomDialog());
    }

    private void showCustomDialog() {
        // สร้าง Dialog พร้อม Custom Layout
        final Dialog dialog = new Dialog(this);
        dialog.setContentView(R.layout.custom_dialog);
        
        // Optional: ทำให้ Dialog ไม่มีมุมโค้ง (ถ้า Layout มี Background เอง)
        // dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        
        // Optional: กำหนดขนาด Dialog
        // dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);

        Button dialogButton = dialog.findViewById(R.id.dialogButtonOK);
        dialogButton.setOnClickListener(v -> {
            dialog.dismiss();
            Toast.makeText(MainActivity.this, "Dismissed!", Toast.LENGTH_SHORT).show();
        });

        // ปิด Dialog เมื่อคลิกนอกพื้นที่ (Default = true)
        dialog.setCanceledOnTouchOutside(true);
        
        dialog.show();
    }
}

ขั้นตอนที่ 5: 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>
                
                
            </intent-filter>
        </activity>

    </application>
</manifest>

การทดสอบ

รันแอป → กดปุ่ม "Click" → จะแสดง Custom Dialog พร้อม Icon, ข้อความ และปุ่ม Dismiss

วิธีสร้าง Custom Alert Dialog ใน Android วิธีสร้าง Custom Alert Dialog ใน Android วิธีสร้าง Custom Alert Dialog ใน Android

💡 แนะนำ: MaterialAlertDialogBuilder (ทันสมัยกว่า)

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

// ใช้งาน
new MaterialAlertDialogBuilder(this)
    .setTitle("Custom Dialog")
    .setMessage("This uses Material Design")
    .setPositiveButton("OK", (dialog, which) -> {})
    .setNegativeButton("Cancel", (dialog, which) -> {})
    .setView(R.layout.custom_dialog) // ใช้ Custom Layout ได้
    .show();

DialogFragment (แนะนำสำหรับ Dialog ที่ซับซ้อน)

public class CustomDialogFragment extends DialogFragment {

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.custom_dialog, null);
        
        Button btn = view.findViewById(R.id.dialogButtonOK);
        btn.setOnClickListener(v -> dismiss());

        return new MaterialAlertDialogBuilder(requireContext())
            .setView(view)
            .create();
    }
}

// ใช้งาน
new CustomDialogFragment().show(getSupportFragmentManager(), "custom_dialog");

AlertDialog vs Dialog vs DialogFragment

Classใช้เมื่อไหร่ข้อดี
AlertDialog.BuilderDialog เรียบง่าย (Title, Message, 1-3 Buttons)ง่าย, เร็ว, Material Design
DialogCustom Layout ทั้งหมด, ไม่ต้องการ Lifecycleควบคุม Layout ได้เต็มที่
DialogFragmentDialog ซับซ้อน, มี Logic, ต้องการ Survive Config ChangeLifecycle Aware, Retain Instance, Backstack