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

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

ภาพรวม

ตัวอย่างนี้สาธิตวิธีสร้าง Custom Dialog แบบเต็มหน้าจอ (Full Screen) ใน Android โดยใช้ AlertDialog.Builder พร้อม Custom Theme และการคำนวณขนาดหน้าจอ

ขั้นตอนที่ 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: สร้าง Custom Theme

ไฟล์ res/values/styles.xml:

<style name="CustomAlertDialog" parent="Theme.AppCompat.Light.Dialog.Alert">
    <item name="android:windowBackground">@drawable/popup_background</item>
    <item name="android:windowMinWidthMajor">100%</item>
    <item name="android:windowMinWidthMinor">100%</item>
</style>

ขั้นตอนที่ 5: สร้าง Drawable Background

ไฟล์ res/drawable/popup_background.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android">
    <solid android:color="#FFFFFF" />
    <corners android:radius="6dp" />
</shape>

ขั้นตอนที่ 6: โค้ด Java หลัก

ไฟล์ src/MainActivity.java:

package com.example.andy.myapplication;

import android.app.Activity;
import android.graphics.Rect;
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;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;

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. ดึงขนาดหน้าจอที่มองเห็นได้
                Rect displayRectangle = new Rect();
                Window window = MainActivity.this.getWindow();
                window.getDecorView().getWindowVisibleDisplayFrame(displayRectangle);
                
                // 2. สร้าง Builder พร้อม Custom Theme
                AlertDialog.Builder builder = new AlertDialog.Builder(
                    MainActivity.this, R.style.CustomAlertDialog);
                
                // 3. Inflate Custom View
                ViewGroup viewGroup = findViewById(android.R.id.content);
                View dialogView = LayoutInflater.from(v.getContext())
                    .inflate(R.layout.customview, viewGroup, false);
                
                // 4. กำหนดขนาดขั้นต่ำ = ขนาดหน้าจอ (Full Screen)
                dialogView.setMinimumWidth((int)(displayRectangle.width() * 1f));
                dialogView.setMinimumHeight((int)(displayRectangle.height() * 1f));
                
                // 5. ตั้งค่า View และแสดง
                builder.setView(dialogView);
                final AlertDialog alertDialog = builder.create();
                
                // 6. จัดการปุ่ม OK ใน Custom View
                Button buttonOk = dialogView.findViewById(R.id.buttonOk);
                buttonOk.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        alertDialog.dismiss();
                    }
                });
                
                alertDialog.show();
            }
        });
    }
}

🔑 โค้ดสำคัญ: ทำให้ Dialog Full Screen

// 1. ดึงขนาดหน้าจอที่มองเห็นได้ (exclude status/navigation bar)
Rect displayRectangle = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(displayRectangle);

// 2. กำหนด Minimum Width/Height ของ Dialog View
dialogView.setMinimumWidth(displayRectangle.width());
dialogView.setMinimumHeight(displayRectangle.height());

// 3. Theme ต้องไม่มี padding/margin ขอบ
// ใช้ android:windowMinWidthMajor/Minor = 100% ใน Theme

วิธีอื่น: ใช้ DialogFragment (แนะนำ)

public class FullScreenDialogFragment extends DialogFragment {
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NORMAL, R.style.FullScreenDialogStyle);
    }
    
    @Override
    public void onStart() {
        super.onStart();
        // ทำให้ Dialog กว้างเต็มหน้าจอ
        Dialog dialog = getDialog();
        if (dialog != null) {
            Window window = dialog.getWindow();
            window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, 
                           ViewGroup.LayoutParams.MATCH_PARENT);
        }
    }
}

// Style
<style name="FullScreenDialogStyle" parent="Theme.AppCompat.Light.Dialog">
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowIsFloating">false</item>
</style>

วิธีอื่น: BottomSheetDialogFragment (Material Design)

public class FullScreenBottomSheet extends BottomSheetDialogFragment {
    @Override
    public void setupDialog(Dialog dialog, int style) {
        super.setupDialog(dialog, style);
        View contentView = View.inflate(getContext(), R.layout.customview, null);
        dialog.setContentView(contentView);
        
        // Full screen
        ((View) contentView.getParent()).setFitsSystemWindows(true);
        
        Button ok = contentView.findViewById(R.id.buttonOk);
        ok.setOnClickListener(v -> dismiss());
    }
    
    @Override
    public int getTheme() {
        return R.style.FullScreenBottomSheetStyle;
    }
}

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

  • Status Bar / Navigation Bar: Full Screen Dialog อาจครอบไม่ถึง System Bars ใช้ WindowInsets หรือ fitsSystemWindows
  • Theme: ใช้ android:windowIsFloating="false" เพื่อไม่ให้เป็น Floating Window
  • Back Press: Dialog จะปิดเมื่อกด Back ควร Override หากต้องการป้องกัน
  • Memory: Full Screen Dialog ใช้หน่วยความจำมากกว่า Dialog ปกติ

วิธีทดสอบ

  1. รันแอปบนอุปกรณ์จริง
  2. กดปุ่ม "Custom Dialog"
  3. จะแสดง Dialog ขยายเต็มหน้าจอ พร้อมเนื้อหาและปุ่ม OK
  4. กด OK หรือ Back เพื่อปิด

📱 Material Design 3 - ใช้ MaterialAlertDialogBuilder

new MaterialAlertDialogBuilder(this, R.style.FullScreenMaterialDialog)
    .setView(R.layout.customview)
    .show();