ภาพรวม
ตัวอย่างนี้สาธิตวิธีสร้าง AlertDialog แบบกำหนดเอง (Custom AlertDialog) โดยใช้ Layout XML แยกต่างหาก ทำให้สามารถออกแบบ UI ได้อย่างอิสระ พร้อม Animation และ Styling ตามต้องการ
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
เปิด Android Studio ไปที่ File → New Project แล้วกรอกข้อมูลที่จำเป็น
ขั้นตอนที่ 2: Layout หลัก (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/buttonShowDialog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:backgroundTint="@color/colorPrimary"
android:padding="15dp"
android:text="Show Custom Dialog"
android:textAllCaps="false"
android:textColor="#ffffff"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
ขั้นตอนที่ 3: Custom Dialog Layout (res/layout/my_dialog.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp">
<!-- Header สีหลัก -->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="80dp"
android:background="@color/colorPrimary">
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_centerInParent="true"
android:src="@drawable/ic_success"
android:contentDescription="Success Icon" />
</RelativeLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Success"
android:textAlignment="center"
android:textAppearance="@style/TextAppearance.MaterialComponents.Headline6" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla eu erat tincidunt lacus fermentum rutrum."
android:textAlignment="center"
android:textAppearance="@style/TextAppearance.MaterialComponents.Body1" />
<Button
android:id="@+id/buttonOk"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="24dp"
android:background="@drawable/button_background"
android:text="OK"
android:textColor="@color/colorPrimary" />
</LinearLayout>
ขั้นตอนที่ 4: Button Background (res/drawable/button_background.xml)
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="https://schemas.android.com/apk/res/android">
<item android:state_pressed="true">
<shape>
<solid android:color="@color/colorPrimary" />
<corners android:radius="6dp" />
</shape>
</item>
<item>
<shape>
<stroke android:width="2dp" android:color="@color/colorPrimary" />
<solid android:color="@android:color/transparent" />
<corners android:radius="6dp" />
</shape>
</item>
</selector>
ขั้นตอนที่ 5: Vector Icon (res/drawable/ic_success.xml)
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="https://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FFFFFF"
android:pathData="M12,2C6.48,2 2,6.48 2,12s4.48,10 10,10 10,-4.48 10,-10S17.52,2 12,2zM10,17l-5,-5 1.41,-1.41L10,14.17l7.59,-7.59L19,8l-9,9z"/>
</vector>
ขั้นตอนที่ 6: MainActivity (src/MainActivity.java)
package com.app.sample;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.buttonShowDialog).setOnClickListener(v -> showCustomDialog());
}
private void showCustomDialog() {
ViewGroup viewGroup = findViewById(android.R.id.content);
View dialogView = LayoutInflater.from(this).inflate(R.layout.my_dialog, viewGroup, false);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(dialogView);
builder.setCancelable(true);
AlertDialog alertDialog = builder.create();
// ตั้งค่าปุ่ม OK ใน Dialog
Button btnOk = dialogView.findViewById(R.id.buttonOk);
btnOk.setOnClickListener(v -> alertDialog.dismiss());
// ทำให้พื้นหลัง Dialog โปร่งใส (Optional)
if (alertDialog.getWindow() != null) {
alertDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
}
alertDialog.show();
}
}
ขั้นตอนที่ 7: Manifest (Manifests/AndroidManifest.xml)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.app.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/Theme.AppCompat.Light.DarkActionBar">
<activity android:name=".MainActivity" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
เทคนิคเพิ่มเติมสำหรับ Custom Dialog
1. DialogFragment (แนะนำสำหรับโปรเจกต์จริง)
public class CustomDialogFragment extends DialogFragment {
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
View view = LayoutInflater.from(requireContext()).inflate(R.layout.my_dialog, null);
AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
builder.setView(view);
// Setup views...
return builder.create();
}
}
// ใช้งาน:
new CustomDialogFragment().show(getSupportFragmentManager(), "custom_dialog");
2. BottomSheetDialogFragment
สำหรับ Dialog ที่เลื่อนขึ้นจากด้านล่าง (Material Design)
3. การตั้งค่าขนาด Dialog
alertDialog.show();
// กำหนดความกว้าง
alertDialog.getWindow().setLayout(
(int) (getResources().getDisplayMetrics().widthPixels * 0.9),
ViewGroup.LayoutParams.WRAP_CONTENT);
การทดสอบ
เชื่อมต่ออุปกรณ์ Android จริง ใน Android Studio คลิก Run - กดปุ่ม "Show Custom Dialog" จะแสดง Dialog สวยงามพร้อม Icon, Title, Message และปุ่ม OK