Android Custom Dialog
Post
Cancel

Custom Dialog

You are developing an Android app and you don’t want to use the default dialog like this:

Custom Dialog

You want something is unique and customizable like this:

Custom Dialog

This post will guide you how to create a custom dialog in Android!

Firstly, create an XML layout for your custom dialog:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TextView
        android:id="@+id/lbMessage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/webView"
        android:layout_centerHorizontal="true"
        android:text="Message"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="75dp"
        android:layout_height="75dp"
        android:layout_below="@+id/lbMessage"
        android:layout_centerHorizontal="true"
        android:src="@drawable/ic_launcher" />

    <Button
        android:id="@+id/btnOK"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/imageView1"
        android:layout_centerInParent="true"
        android:text="OK" />

</RelativeLayout>

 

With those upper XML, we will have a dialog like this:

Custom Dialog

Next, In the code, you need to create a Dialog object using custom layout which we just created:

Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.custom_dialog_layout);

 

You can set the title for dialog, and handle all the controls in custom layout:

dialog.setTitle("Confirm");

TextView lbMessage = (TextView)dialog.findViewById(id.lbMessage);
Button btnOK = (Button)dialog.findViewById(id.btnOK);

lbMessage.setText("This is the message of dialog!");

btnOK.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        dialog.dismiss();
    }
});

 

Finally, don’t forget to show the dialog:

dialog.show();

 

And this is the result:

The example this post provided is very simple. You can customize it to whatever you want! :beauty:

Source Code:

https://drive.google.com/file/d/0BzvV1wN-WHWwd1ZSM0h3eDFLWFk/edit?usp=sharing

This post is licensed under CC BY 4.0 by the author.