19

How to display custom dialog as a center of the container?

Dialog customdialog = new Dialog(this,android.R.style.Theme_Translucent_NoTitleBar); 
Window window = customdialog.getWindow();
window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
window.setGravity(Gravity.CENTER);

R.style.Theme_Translucent_NoTitleBar - is used to remove border for cutomdialog. Once i used this line the dialog will appear at the topleft corner of the tablet?

Can anyone help me to solve this issue?

slezadav
  • 6,104
  • 7
  • 40
  • 61
Kamal
  • 195
  • 1
  • 1
  • 9

4 Answers4

52

Change the fill_parent to wrap_content.I hope this will be the issue the dialog appear at the corner of the activity.It takes the space of whole layout.So changing this may help you to get what you realy wanted.

Window window = customdialog.getWindow();
window.setLayout(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
window.setGravity(Gravity.CENTER);

Use above code after dialog.show() statement

Jitendra
  • 1,015
  • 9
  • 24
Sreedev
  • 6,563
  • 5
  • 43
  • 66
  • 1
    Accepting the answer and upvoting it will help us both to improve the reputation So please do the same with this ans @Kamal So happy to help you out.:-) – Sreedev May 02 '12 at 11:46
  • But i want without giving window.setLayout(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); is it possible – Abhijit Chakra Feb 03 '15 at 14:42
  • Tried window.setDimAmount(0.5f); but it is not working. Then took Root layout to main layout and set width and height to fill parent , background semi transparent but layout coming in top. – Prashanth Debbadwar Aug 25 '16 at 18:24
14

I added this to the dialog's custom style and it worked fine.

<item name="android:layout_gravity">center</item>

My dialog's width and height are set to wrap_content. The style's parent is

parent="@android:style/Theme.Light"

Shabnam Sarup
  • 261
  • 2
  • 3
  • Indeed I did as suggested by Sreedev but I couldn't get my dialog at the center. Adding this parameter in my style solved the issue for me. – Claude Hangui Apr 11 '19 at 13:20
0

I will go for this piece of code:

        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        Window window = dialog.getWindow();
        lp.copyFrom(window.getAttributes());
        //This makes the dialog take up the full width
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.MATCH_PARENT;
        window.setAttributes(lp);

Where dialog, is the dialog object to be shown. Inside of the layout of the dialog you can define the view of the layout as you wish: centered or not.

Juan Pedro Martinez
  • 1,924
  • 1
  • 15
  • 24
0

I use this code and the problem solved

Window window = alertDialog.getWindow();
window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
window.setGravity(Gravity.CENTER);
Maysam R
  • 915
  • 10
  • 12