Android : How to create custom dialog

โดยปกติ Android จะมี AlertDialog ให้เราเรียกใช้ได้เลย ต้องการกำหนดข้อความอะไรก็สามาถเรียกฟังก์ชัน .setMessage(…) ได้ กำหนดให้มีปุ่มกดได้ก็เรียกฟังก์ชัน .setPositiveButton(…) ก็มีปุ่มพร้อมกดให้เลย

แต่ถ้าเราต้องการเพิ่มเติมรูปภาพ หรือออปชันอื่นๆ ก็อาจทำไม่ได้ หรือทำได้แต่ไม่โดนใจเรา ซึ่งเราก็มีอีกทางเลือกคือสร้าง Custom Dialog ขึ้นมาเอง กำหนดหน้าตาของ Dialog layout เองทั้งหมด แบบนี้ก็จะได้ตามที่เราต้องการเลย เช่น สมมติว่าต้องการเพิ่มรูปภาพให้กดในรูปได้ (ImageButton) หรือต้องการเพิ่มข้อความให้กดแล้วไปเว็บต่อได้ (TextView) ก็ทำได้เลย โดยมีขั้นตอนการสร้าง Custom Dialog ดังนี้Create XML Layout

1.Create XML layout สร้างรูปแบบของ Dialog ว่าต้องการให้มีอะไรบ้าง ตัวอย่าง เป็นการสร้าง Dialog ที่แสดงรูปไอคอนแอปฯ ชื่อแอปฯ และ ปุ่ม OK

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@color/black"
    android:orientation="vertical">

<ImageView
    android:id="@+id/image"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@mipmap/ic_launcher"
    android:layout_margin="5dp" />

<TextView
    android:id="@+id/text"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/app_name"
    android:textColor="@color/white"/>

 <Button
    android:id="@+id/ButtonOK"
    android:layout_width="50dp"
    android:layout_height="wrap_content"
    android:text="OK"
    android:layout_margin="5dp"/>
</LinearLayout>

2.Create Java Custom Dialog สร้างฟังก์ชัน Custom Dialog โดยในตัวอย่างจะเรียกใช้ Custom Dialog ตอนกดปุ่ม Back (onBackPressed())

@Override
public void onBackPressed() {
 CustomDialog();

}

private void CustomDialog(){

// custom dialog
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.custom_dialog);
// ---- Button ----
Button b_ok = dialog.findViewById(R.id.ButtonOK);

b_ok.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

 dialog.cancel();
}
});
}

จากตัวอย่างเมื่อกดปุ่ม Back บนสมาร์ทโฟน จะมีหน้าต่าง Custom Dialog ขึ้นมา พอกดปุ่ม OK หน้าต่างก็หายไป

You may also like...