Android custom dialog example

In this tutorial, we show you how to create a custom dialog in Android. See following steps :

  1. Create a custom dialog layout (XML file).
  2. Attach the layout to Dialog.
  3. Display the Dialog.
  4. Done.

P.S This project is developed in Eclipse 3.7, and tested with Android 2.3.3.

Note
You may also interest to read this custom AlertDialog example.

1 Android Layout Files

Two XML files, one for main screen, one for custom dialog.

File : res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
 
    <Button
        android:id="@+id/buttonShowCustomDialog"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Custom Dialog" />
 
</LinearLayout>

File : res/layout/custom.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
 
    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="5dp" />
 
    <TextView
        android:id="@+id/text"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textColor="#FFF" 
        android:layout_toRightOf="@+id/image"/>/>
 
     <Button
        android:id="@+id/dialogButtonOK"
        android:layout_width="100px"
        android:layout_height="wrap_content"
        android:text=" Ok "
        android:layout_marginTop="5dp"
        android:layout_marginRight="5dp"
        android:layout_below="@+id/image"
        />
 
</RelativeLayout>

2. Activity

Read the comment and demo in next step, it should be self-explorary.

File : MainActivity.java

package com.mkyong.android;
 
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
 
public class MainActivity extends Activity {
 
	final Context context = this;
	private Button button;
 
	public void onCreate(Bundle savedInstanceState) {
 
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
 
		button = (Button) findViewById(R.id.buttonShowCustomDialog);
 
		// add button listener
		button.setOnClickListener(new OnClickListener() {
 
		  @Override
		  public void onClick(View arg0) {
 
			// custom dialog
			final Dialog dialog = new Dialog(context);
			dialog.setContentView(R.layout.custom);
			dialog.setTitle("Title...");
 
			// set the custom dialog components - text, image and button
			TextView text = (TextView) dialog.findViewById(R.id.text);
			text.setText("Android custom dialog example!");
			ImageView image = (ImageView) dialog.findViewById(R.id.image);
			image.setImageResource(R.drawable.ic_launcher);
 
			Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
			// if button is clicked, close the custom dialog
			dialogButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					dialog.dismiss();
				}
			});
 
			dialog.show();
		  }
		});
	}
}

3. Demo

Start it, the “main.xml” layout is display.

android custom dialog example

Click on the button, display custom dialog “custom.xml” layout, if you click on the “OK” button, dialog box will be closed.

android custom dialog example

Download Source Code

Download it – Android-Custom-Dialog-Example.zip (16 KB)

References

  1. Android Dialog Javadoc
  2. Android Dialog example
  3. Android relative layout example
  4. Android prompt dialog (custom AlertDialog) example
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

  • Pingback: kagen water()

  • Pingback: alkaline water()

  • Pingback: alkaline water()

  • Pingback: water ionizers()

  • Pingback: watch tv show episodes()

  • Pingback: stream movies()

  • Pingback: watch movies online free()

  • Pingback: Click here to download()

  • Pingback: Blue Coaster33()

  • knvchowdary

    Yes,Ur guide is ultimate,in same way shall I keep more than one images in DialogBox

  • http://[email protected] chris

    Having trouble implimenting this, produces error when i access the option dialogs however, when i comment out the onclick meathod, it shows the dialog with out problem.
    Any ideas?

    package com.example.joybot;
     
    import android.os.Bundle;
    import android.app.Activity;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.webkit.WebView;
    import android.webkit.WebSettings;
    import android.widget.EditText;
    import android.widget.RadioButton;
    import android.widget.RadioButton.*;
    import android.widget.TextView;
    import android.widget.Button;
    import com.MobileAnarchy.Android.Widgets.Joystick.JoystickClickedListener;
    import com.MobileAnarchy.Android.Widgets.Joystick.JoystickMovedListener;
    import com.MobileAnarchy.Android.Widgets.Joystick.JoystickView;
    import android.app.ActionBar;
    import android.app.Dialog;
    import android.content.Context;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button.*;
    //import android.location.*;
    //import com.google.android.maps.*;
    public class MainActivity extends Activity {
        ActionBar actbar;
        TextView txtX, txtY;
        JoystickView joystick;
        WebView mapper;
        int joyx, joyy;
        WebSettings webSettings;
        final Context context = this;
     
        //MapView maptrack;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
     
          //  webSettings = myWebView.getSettings();
           // webSettings.setJavaScriptEnabled(true);
            joystick = (JoystickView)findViewById(R.id.joystickView);
            mapper = (WebView)findViewById(R.id.webView);
            webSettings = mapper.getSettings();
            webSettings.setBuiltInZoomControls(true);
            mapper.loadUrl("http://www.google.com.au");
            joystick.setOnJostickMovedListener(_listener);
     
     
        }
     
        private JoystickMovedListener _listener = new JoystickMovedListener() {
     
            @Override
            public void OnMoved(int pan, int tilt) {
                //txtX.setText(Integer.toString(pan));
                joyx=pan;
                joyy=tilt;
                //txtY.setText(Integer.toString(tilt));
            }
     
            @Override
            public void OnReleased() {
               // txtX.setText("released");
               // txtY.setText("released");
                joyx=0;
                joyy=0;
     
            }
     
            public void OnReturnedToCenter() {
               // txtX.setText("stopped");
                joyx=0;
                joyy=0;
                //txtY.setText("stopped");
            };
        };
     
     
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle item selection
            switch (item.getItemId()) {
                case R.id.action_settings:
                    //setContentView(R.layout.activity_options);
                    final Dialog dialog = new Dialog(context);
                    dialog.setContentView(R.layout.activity_options);
                    dialog.setTitle("Options");
                    RadioButton radmap = (RadioButton) findViewById(R.id.radioButton);
                    RadioButton radcam = (RadioButton) findViewById(R.id.radioButton2);
                    EditText server = (EditText) findViewById(R.id.editText);
                    EditText cmdport = (EditText) findViewById(R.id.editText2);
                    EditText imgport = (EditText) findViewById(R.id.editText3);
                    Button LLButton = (Button) findViewById(R.id.button);
                    Button SButton = (Button) findViewById(R.id.button2);
                    Button CButton = (Button) findViewById(R.id.button3);
                    CButton.setOnClickListener(new Button.OnClickListener(){
                        @Override
                        public void onClick(View v) {
                           dialog.dismiss();
                        }
                    });
                    Button ConButton = (Button) findViewById(R.id.button4);
                    Button DisButton = (Button) findViewById(R.id.button5);
     
                    // set the custom dialog components - text, image and button
     
     
                    dialog.show();
                    return true;
                }
            return false;
     
            }
    }
  • Anonymous

    Thank you very much. Me too searching for it.

  • Joe

    Hi mkYong, First of all congratulations for your demos, are so useful.

    I’m new on the android world and i have a problem, i’m trying to show a dialog when i choose a concrete option in my spinner, but when i do this, my application crashes and stops the program.

    The code is something like this:

    public void onItemSelected(final AdapterView parent, View view, int pos,long id) {

    String addSM = parent.getItemAtPosition(pos).toString();

    if (addSM == “A?adir”){

    // custom dialog
    final Dialog dialog = new Dialog(controlador.context);
    dialog.setContentView(R.layout.dialog_afegirsuper);
    dialog.setTitle(“Title…”);

    // set the custom dialog components – text, image and button
    TextView text = (TextView) dialog.findViewById(R.id.text);
    text.setText(“Android custom dialog example!”);

    Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
    // if button is clicked, close the custom dialog
    dialogButton.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
    dialog.dismiss();
    }
    });

    dialog.show();
    }
    }

    thanks a lot for any solution.

    • Ricardo A. Hermosilla Carrillo

      When you compare strings, you must do it like this:
      if(addSM.equals(“Añadir”))
      The way you are doing it is wrong. Try this change and then make a reply if everything is going well.

      Regards

      • Binh Lee

        @Ricardo A.Hermosilla Carrillo
        Yes, you said right. Better way is using if(“Añadir”.equals(addSM)) this will
        prevent the case addSM is null too.

  • Eagle_Eye

    Thanx Very Much Sir..
    It Helped Me A Lot…
    Thanx Very Very Much Again..
    :D

  • Monica

    Very useful example. I tried to do a simpler example myself and initially I wrote it like this:

    public class MainActivity extends Activity {

    Context mContext = null;
    Dialog dialog = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mContext = getApplicationContext();
    dialog = new Dialog(mContext);

    dialog.setContentView(R.layout.custom_dialog);

    dialog.setTitle(“Custom Dialog”);
    TextView text = (TextView) dialog.findViewById(R.id.text);
    text.setText(“Hello, this is a custom dialog!”);
    ImageView image = (ImageView) dialog.findViewById(R.id.image);
    image.setImageResource(R.drawable.ic_launcher);

    dialog.show();
    }

    }

    The result was that the application crashed right after launching. Then I compared it to your example and I saw that the assignment

    Context mContext = null;

    should be instead

    Context mContext = this;

    and also the assignment to mContext inside the method becomes no longer necessary. I would be very grateful if someone could explain why is this so. It seems reasonable, though I can’t grasp the full meaning.

    Thank you, mkyong!!

  • Ben

    To remove the dialog’s title,

    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

    before you set the layout (with dialog.setContentView(R.layout.education_details_layout);)

  • Ben

    Thank you, worked like a charm

  • Pingback: Popup listView scroll and with imgaes : Android Community - For Application Development()

  • Pingback: default alert dialog buttons height and width : Android Community - For Application Development()

  • Pingback: Listview with onClick popup information : Android Community - For Application Development()

  • http://www.verious.com Giancarlo Leonio

    Great post! Thank you. I compiled a list of some top resources for creating a custom dialog box in android. I included your post. Check it out/ feel free to share. http://www.verious.com/board/Giancarlo-Leonio/customizing-dialog-boxes-in-android/ Hope this can be useful to other developers too. :)

  • Pingback: How do I start an xml activity from a dialog? : Android Community - For Application Development()

  • Prasad

    Nice tutorial. I have a question. Question is what if I want to return some value to activity from this dialog. Here is my example.

    Activity layout file : activity_my_dialog.xml

    &lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
        xmlns:tools=&quot;http://schemas.android.com/tools&quot;
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;match_parent&quot;
        android:orientation=&quot;vertical&quot;
        tools:context=&quot;.MyDialogActivity&quot; &gt;
     
        &lt;Button
            android:layout_width=&quot;wrap_content&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:text=&quot;Click to Add Details&quot; 
            android:id=&quot;@+id/btn&quot;/&gt;
     
        &lt;EditText 
            android:layout_width=&quot;fill_parent&quot;
            android:layout_height=&quot;fill_parent&quot;
            android:id=&quot;@+id/etd&quot;
            /&gt;
    &lt;/LinearLayout&gt;

    Dialog Layout File : education_details_layout.xml

    &lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
    &lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:orientation=&quot;vertical&quot; &gt;
     
    	&lt;TextView 
    	    android:layout_width=&quot;fill_parent&quot;
    	    android:layout_height=&quot;wrap_content&quot;
    	    android:text=&quot;Name&quot;
    	    /&gt;
    	&lt;EditText 
    	    android:layout_width=&quot;fill_parent&quot;
    	    android:layout_height=&quot;wrap_content&quot;
    	    android:id=&quot;@+id/ednm&quot;
    	    /&gt;
     
    	&lt;TextView 
    	    android:layout_width=&quot;fill_parent&quot;
    	    android:layout_height=&quot;wrap_content&quot;
    	    android:text=&quot;City&quot;
    	    /&gt;
    	&lt;EditText 
    	    android:layout_width=&quot;fill_parent&quot;
    	    android:layout_height=&quot;wrap_content&quot;
    	    android:id=&quot;@+id/edcity&quot;
    	    /&gt;
    	&lt;TextView 
    	    android:layout_width=&quot;fill_parent&quot;
    	    android:layout_height=&quot;wrap_content&quot;
    	    android:text=&quot;Highest Qualification&quot;
    	    /&gt;
    	&lt;EditText 
    	    android:layout_width=&quot;fill_parent&quot;
    	    android:layout_height=&quot;wrap_content&quot;
    	    android:id=&quot;@+id/edq&quot;
    	    /&gt;
     
    	&lt;LinearLayout 
    	    android:layout_width=&quot;fill_parent&quot;
    	    android:layout_height=&quot;wrap_content&quot;
    	    android:orientation=&quot;horizontal&quot;
    	    &gt;
    	&lt;Button 
    	    android:layout_width=&quot;wrap_content&quot;
    	    android:layout_height=&quot;wrap_content&quot;
    	    android:text=&quot;Add&quot;
    	    android:id=&quot;@+id/btnadd&quot;
    	    /&gt;
    	&lt;Button
    	    android:layout_width=&quot;wrap_content&quot;
    	    android:layout_height=&quot;wrap_content&quot;
    	    android:text=&quot;Cancel&quot;
    	    android:id=&quot;@+id/btncancel&quot;
    	    /&gt;
    	&lt;/LinearLayout&gt;
    &lt;/LinearLayout&gt;

    Creating custom dialog : Mydialog.java

    package com.myclass.mydialog;
     
    import android.app.Dialog;
    import android.content.Context;
    import android.os.Bundle;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
     
    public class Mydialog extends Dialog implements android.view.View.OnClickListener{
    	Context context;
    	Button btnadd, btncancel;
    	EditText etnm, etncity, etnq;
    	String result;
    	public Mydialog(Context context) {
    		super(context);
    		this.context = context;
    	}
     
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		// TODO Auto-generated method stub
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.education_details_layout);
    		btnadd = (Button) findViewById(R.id.btnadd);
    		btncancel = (Button) findViewById(R.id.btncancel);
     
    		etnm = (EditText) findViewById(R.id.ednm);
    		etncity = (EditText) findViewById(R.id.edcity);
    		etnq = (EditText) findViewById(R.id.edq);
    		result = &quot;&quot;;
     
    		btnadd.setOnClickListener(this);
    	}
     
    	public String showMyDialog()
    	{
    		show();
    		return result;
    	}
    	@Override
    	public void onClick(View v) {
    		// TODO Auto-generated method stub
    		if(v == btnadd)
    		{
    			result = etnm.getText().toString()+&quot; - &quot;+etncity.getText().toString()+&quot; - &quot;+etnq.getText().toString();
    			hide();
    		}
    		else
    		if(v == btncancel)
    		{
    			result = &quot;&quot;;
    			dismiss();
    		}
    	}
     
    }

    Main Java File : MyDialogActivity.java

    package com.myclass.mydialog;
     
    import android.os.Bundle;
    import android.app.Activity;
    import android.app.Dialog;
    import android.view.Menu;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;
     
    public class MyDialogActivity extends Activity implements OnClickListener {
    	Button btn;
    	EditText et;
    	Mydialog d;
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.activity_my_dialog);
    		btn = (Button) findViewById(R.id.btn);
    		et = (EditText) findViewById(R.id.etd);
    		d = new Mydialog(this);
     
    		btn.setOnClickListener(this);
     
    	}
     
    	@Override
    	public boolean onCreateOptionsMenu(Menu menu) {
    		// Inflate the menu; this adds items to the action bar if it is present.
    		getMenuInflater().inflate(R.menu.activity_my_dialog, menu);
    		return true;
    	}
     
    	@Override
    	public void onClick(View v) {
    		// TODO Auto-generated method stub
    		if(v == btn)
    		{
    			d.show();
    			String result = d.result;
     
    			if(result.equals(&quot;&quot;))
    			{
    				Toast.makeText(getBaseContext(), &quot;Action cancelled&quot;, Toast.LENGTH_LONG).show();
    			}
    			else
    			{
    				et.append(&quot;\n&quot;+result);
    			}
    		}
    	}
    }

    What ever details I am accepting from dialog box needs to be appended in the EditText component in main activity.

    Please help me. Thanks in advance.

    • Prasad

      I got the answer myself. Answer is to add OnDismissListener() to dialog as below:

      MyDialogActivity.java

      package com.myclass.mydialog;
       
      import android.os.Bundle;
      import android.app.Activity;
      import android.app.Dialog;
      import android.content.DialogInterface;
      import android.content.DialogInterface.OnDismissListener;
      import android.view.Menu;
      import android.view.View;
      import android.view.View.OnClickListener;
      import android.widget.Button;
      import android.widget.EditText;
      import android.widget.Toast;
       
      public class MyDialogActivity extends Activity implements OnClickListener {
      	Button btn;
      	EditText et;
      	Mydialog d;
      	@Override
      	protected void onCreate(Bundle savedInstanceState) {
      		super.onCreate(savedInstanceState);
      		setContentView(R.layout.activity_my_dialog);
      		btn = (Button) findViewById(R.id.btn);
      		et = (EditText) findViewById(R.id.etd);
      		d = new Mydialog(this);
       
      		btn.setOnClickListener(this);
      		d.setOnDismissListener(new OnDismissListener() {
       
      			@Override
      			public void onDismiss(DialogInterface dialog) {
      				// TODO Auto-generated method stub
      				String result = d.getResult();
      				if(result.equals(&quot;&quot;))
      				{
      					Toast.makeText(getBaseContext(), &quot;Action cancelled&quot;, Toast.LENGTH_LONG).show();
      				}
      				else
      				{
      					et.append(&quot;\n&quot;+result);
      				}
      			}
      		});
      	}
       
      	@Override
      	public boolean onCreateOptionsMenu(Menu menu) {
      		// Inflate the menu; this adds items to the action bar if it is present.
      		getMenuInflater().inflate(R.menu.activity_my_dialog, menu);
      		return true;
      	}
       
      	@Override
      	public void onClick(View v) {
      		// TODO Auto-generated method stub
      		if(v == btn)
      		{
      			d.show();
       
       
      		}
      	}
      }
  • Nibin

    very nice example…

  • Pingback: Eigenen AlertBuilder, wie Lieferheld - Android-Hilfe.de()

  • hasith31

    very useful!
    thank you!

  • Pingback: Android: dailog box with android profile picture : Android Community - For Application Development()

  • Pingback: Custom Alert Box : Android Community - For Application Development()

  • harvey
  • http://www.fb.com/Whitehathacker LinsLouis

    Great Tutorial..Worked well….thanks

  • http://www.fb.com/Whitehathacker LinsLouis

    This is Very easy Tutorial for Beginners Like Me……Thank you very much…….

  • linh

    it don’t run in Android 3.0 (API 11)

    • linh

      oh, I sr ! it work well :)

  • alireza77sh

    that was really nice example for beginners. thank you very much.

  • Mila

    Perfect, straight to the point!

  • Chi

    Hi, mkYong
    The section
    dialogButton.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
    dialog.dismiss();
    }
    });
    crashed on my app.
    But not on your sample code.
    What could happened?
    Thanks

    • Luki R Rompis

      have you import this? :)

      import android.view.View.OnClickListener;
  • Iván Sánchez

    Thank you very much for the post! Just I’m searching for it.

  • Pingback: Android prompt user input dialog example()

  • Pingback: Android Tutorial()

  • rajini

    hi thanks a lot….but by using this code,my dialog box is dismissed without clicking ok button .If i click anywhere on window it will be closed …can u tell me the reason???thank u…..

  • Nirav Nimbark

    Can you provide any simple example of zoom in,zoom out…in android?

  • Nirav Nimbark

    Your website is good examples for beginner.. keep it up..

  • Carmine

    Thanks very much. With this tutorial I have understood which one was the error made lost me many hours.
    Thanksssssss.

  • Jerry

    Hi could you please tell me how can I add this into my existing application. I understand how to add the xml layout files, but not sure where to add the .java file. Is it under the src folder ? I tried adding your two xml files and the .java file to my app but when I launch the app nothing appears. not even an error message

  • Jerry

    Hi could you please tell me how can I add this into my existing application. I understand how to add the xml layout files, but not sure where to add the .java file. Is it under the src folder ? I tried adding your two xml files and the .java file to my app but when I launch the app nothing appears