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

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

ภาพรวม

ตัวอย่างนี้สาธิตวิธีสร้าง Custom Dialog ใน Android โดยใช้ AlertDialog.Builder และ inflate Custom View จาก XML Layout

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

สร้างโปรเจกต์ Android ใหม่ใน Android Studio

ขั้นตอนที่ 2: เพิ่ม Layout หลัก

ไฟล์ res/layout/activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/parent"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:gravity="center"
    android:orientation="vertical">
    <Button
        android:id="@+id/customDialog"
        android:text="Custom Dialog"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

ขั้นตอนที่ 3: สร้าง Custom View Layout

สร้างไฟล์ res/layout/customview.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="match_parent"
    android:orientation="vertical">
    <LinearLayout
        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="Success"
            android:textAlignment="center"
            android:textAppearance="@style/TextAppearance.AppCompat.Headline" />
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:text="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla eu erat tincidunt lacus fermentum rutrum."
            android:textAlignment="center"
            android:textAppearance="@style/TextAppearance.AppCompat.Medium" />
        <Button
            android:id="@+id/buttonOk"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginTop="15dp"
            android:background="@color/colorPrimary"
            android:text="Ok"
            android:textColor="#FFF" />
    </LinearLayout>
</LinearLayout>

ขั้นตอนที่ 4: โค้ด Java

ไฟล์ src/MainActivity.java:

package com.example.andy.myapplication;

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class MainActivity extends AppCompatActivity {

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        findViewById(R.id.customDialog).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 1. สร้าง Builder
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                
                // 2. Inflate Custom View
                ViewGroup viewGroup = findViewById(android.R.id.content);
                View dialogView = LayoutInflater.from(v.getContext())
                    .inflate(R.layout.customview, viewGroup, false);
                
                // 3. ตั้งค่า View ให้ Dialog
                builder.setView(dialogView);
                
                // 4. สร้างและแสดง Dialog
                AlertDialog alertDialog = builder.create();
                alertDialog.show();
                
                // 5. (Optional) จัดการปุ่มใน Custom View
                Button buttonOk = dialogView.findViewById(R.id.buttonOk);
                buttonOk.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        alertDialog.dismiss();
                    }
                });
            }
        });
    }
}

🔧 ปรับปรุงจากต้นฉบับ: เพิ่มการจัดการปุ่ม OK

โค้ดต้นฉบับไม่ได้จัดการปุ่ม OK ใน Custom View ผมเพิ่มการ dismiss dialog เมื่อกด OK

รูปแบบ Custom Dialog อื่นๆ

1. Dialog แบบไม่มี Title (Full Custom)

AlertDialog.Builder builder = new AlertDialog.Builder(this);
View dialogView = LayoutInflater.from(this).inflate(R.layout.customview, null);
builder.setView(dialogView);
AlertDialog dialog = builder.create();

// ทำให้ไม่มีพื้นหลังมุมโค้ง (ถ้าต้องการ)
dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
dialog.show();

2. ใช้ DialogFragment (แนะนำสำหรับ Lifecycle)

public class CustomDialogFragment extends DialogFragment {
    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.customview, null);
        builder.setView(view);
        // setup views...
        return builder.create();
    }
}

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

3. Bottom Sheet Dialog (Material Design)

BottomSheetDialog dialog = new BottomSheetDialog(this);
View view = LayoutInflater.from(this).inflate(R.layout.customview, null);
dialog.setContentView(view);
dialog.show();

⚠️ ข้อควรระวัง

  • Custom View ต้องมี Layout params ที่เหมาะสม (wrap_content/match_parent)
  • Dialog มีขนาดสูงสุด จัดการ ScrollView หากเนื้อหายาว
  • ใช้ DialogFragment แทน Dialog โดยตรง เพื่อจัดการ Lifecycle ได้ดีกว่า (Rotation, etc.)
  • Theme: ใช้ Theme.AppCompat.Light.Dialog.Alert หรือ Custom theme

วิธีทดสอบ

  1. รันแอปบนอุปกรณ์จริง
  2. กดปุ่ม "Custom Dialog"
  3. จะแสดง Dialog พร้อม Custom Layout (Title, Message, OK Button)
  4. กด OK จะปิด Dialog