Android: How to create a Custom Dialog box?

Android Custom Dialog Box, Custom Alert Dialog,

Create your own custom xml for custom dialog in layout folder like below.

Step 1

custom_dialog.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#ffe3ad"
    android:gravity="center"
    android:orientation="vertical"
    android:padding="10dip" >

    <TextView
        android:id="@+id/textview_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dip"
        android:text="This Custom Diaglog"
        android:textColor="#000000"
        android:textSize="15sp"
        android:textStyle="bold" />

    <LinearLayout
        android:id="@+id/layout_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textview_title"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dip" >

        <Button
            android:id="@+id/button_yes"
            android:layout_width="100dip"
            android:layout_height="50dip"
            android:text="Yes"
            android:textStyle="bold" />

        <Button
            android:id="@+id/button_no"
            android:layout_width="100dip"
            android:layout_height="50dip"
            android:text="No"
            android:textStyle="bold" />
    </LinearLayout>

</RelativeLayout>

Step 2:

Add Below code in your .java file where you would like to show custom dialog.

private void showCustomDialog(){
		LayoutInflater myLayoutInflater = LayoutInflater.from(this);
		final View deleteDialogView = myLayoutInflater.inflate(R.layout.custom_dialog, null);
		final AlertDialog myAlertDialog = new AlertDialog.Builder(this).create();
		myAlertDialog.setView(deleteDialogView);
		deleteDialogView.findViewById(R.id.button_yes).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				//your business logic 
				myAlertDialog.dismiss();
			}
		});
		deleteDialogView.findViewById(R.id.button_no).setOnClickListener(new OnClickListener() {

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

Step 3:

Write below line to call function of dialog in any button click or anywhere you like to show.

showCustomDialog();

 

Leave a comment

Your email address will not be published. Required fields are marked *