How to make an alert dialog fill 90% of screen size?
Asked Answered
M

34

361

I can create and display a custom alert dialog just fine but even so I have android:layout_width/height="fill_parent" in the dialog xml it is only as big as the contents.

What I want is dialog that fills the entire screen except maybe a padding of 20 pixel. Then the image that is part of the dialog would automatically stretch to the full dialog size with fill_parent.

Merryman answered 21/2, 2010 at 16:27 Comment(0)
F
381

According to Android platform developer Dianne Hackborn in this discussion group post, Dialogs set their Window's top level layout width and height to WRAP_CONTENT. To make the Dialog bigger, you can set those parameters to MATCH_PARENT.

Demo code:

    AlertDialog.Builder adb = new AlertDialog.Builder(this);
    Dialog d = adb.setView(new View(this)).create();
    // (That new View is just there to have something inside the dialog that can grow big enough to cover the whole screen.)

    WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
    lp.copyFrom(d.getWindow().getAttributes());
    lp.width = WindowManager.LayoutParams.MATCH_PARENT;
    lp.height = WindowManager.LayoutParams.MATCH_PARENT;
    d.show();
    d.getWindow().setAttributes(lp);

Note that the attributes are set after the Dialog is shown. The system is finicky about when they are set. (I guess that the layout engine must set them the first time the dialog is shown, or something.)

It would be better to do this by extending Theme.Dialog, then you wouldn't have to play a guessing game about when to call setAttributes. (Although it's a bit more work to have the dialog automatically adopt an appropriate light or dark theme, or the Honeycomb Holo theme. That can be done according to http://developer.android.com/guide/topics/ui/themes.html#SelectATheme )

Flexuous answered 8/7, 2011 at 22:43 Comment(13)
Whether I don't understand the answer, or it doesn't work for me.Tellurize
It's also worth noting that this solution is not screen size specific -- it will work on any sized phone/tablet/whatever, whereas the accepted answer has to be adjusted to a specific size.Flexuous
It doesn't seem to be true that dialogs are wrap_content wide. Things get made narrower and cut off. The dialog is seem to be set to some maximum predetermined width.Humidistat
@Peter Ajtai I know what you mean. I think the root element of the view hierarchy must not be WRAP_CONTENT because of the reasons you mention, but the Window that displays the view hierarchy has it's own layout_width and layout_height and I think that's what Dianne was referring to.Flexuous
I dont get how this answers the question? Does the code suggested by @Flexuous make the Dialog to be 90% of the screen? Cause I dont see it. The dialog is just set to fill_width, so thats 100%, not 90%, right?Murraymurre
@Ted, the theme used by AlertDialog has a margin. So the result does not reach to the edge of the screen, it fills about 90% of it. (It's definitely not exactly 90%, just an aesthetic approximation of 90%)Flexuous
Aha, I see. I tried it, and it works. The question is then, why cant I get the same behaviour with a Dialog? I tried margin all over the place... =)Murraymurre
Just calling d.getWindow().getAttributes().width = WindowManager.LayoutParams.FILL_PARENT; before calling show() will do the trick. Also, I've had some issues with the given method as background of the dialog was becoming non-transparent. As soon as removed copyFrom(() the problem fixed itself.Avril
@Avril Yeah, the copy is probably overkill. I'm surprised though, that reversing the order worked for you. It's been a while but I remembered that being important.Flexuous
It works , but how can i add a Button to this new View(this) ('Dialog d = adb.setView(new View(this)).create();), when i use LinearLayout` instead of View ,the dialog becomes smallPotman
This worked for me, except I wrote an actual pixel value to width (using values from koma's method), but the only difference was that the background wasn't greyed out.Ranchero
setAttributes(lp); after the .show() method did the trick. I was calling it before. I thought only the setContentView() should be called after, guess what, living and learning. Thanks.Rafaelle
I case of Dialog, this answer only work when you add setcontentview() first and put rest of code after that.Dentate
M
258

Try wrapping your custom dialog layout into RelativeLayout instead of LinearLayout. That worked for me.

Madonna answered 24/3, 2013 at 1:47 Comment(7)
it has for me as well. Can anyone explain the reason!!Vespertilionine
Is this the way RelativeLayout is supposed to work or a happy accident that could go away?Indecision
It's 2019 and this still works. Cheers! Should indeed be the accepted answer.Sagittal
@Madonna could you explain the answer? That worked for me. Thank you!Hibernaculum
OMG, My RecyclerView never displays full height or it's height always 0 and then with this it works perfectly after a day trying many solutions. Why is RelativeLayout but others?Nance
Could you explain the reason?Legere
It's 2023, and it's still working! GRATE!!Tegantegmen
M
120

Even simpler just do this:

int width = (int)(getResources().getDisplayMetrics().widthPixels*0.90);
int height = (int)(getResources().getDisplayMetrics().heightPixels*0.90);

alertDialog.getWindow().setLayout(width, height);
Maladapted answered 3/11, 2015 at 9:46 Comment(6)
minor note: getResources() is available in the Activity context.Solange
This answer was very helpful for the scenario of trying to recreate a dialog in onCreate after device rotation. In this case, we can't rely on the width/height of anything in the layout, because it hasn't been created yet; but the physical width/height of the device are still available.Undressed
If you want to change only one dimension, pass ViewGroup.LayoutParams.WRAP_CONTENT as one of the parametersTowhaired
This is the best solution for me.Shawnna
Best, simplest solutionStovall
This worked for me, when I put it in onStart of DialogFragment. Tried placing in some other lifecycle callbacks, but didn't worked.Moldboard
R
89

Specifying FILL_PARENT on the dialog window, like others suggested, did not work for me (on Android 4.0.4), because it just stretched the black dialog background to fill the whole screen.

What works fine is using the minimum display value, but specifying it within the code, so that the dialog takes 90% of the screen.

So:

Activity activity = ...;
AlertDialog dialog = ...;

// retrieve display dimensions
Rect displayRectangle = new Rect();
Window window = activity.getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(displayRectangle);

// inflate and adjust layout
LayoutInflater inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.your_dialog_layout, null);
layout.setMinimumWidth((int)(displayRectangle.width() * 0.9f));
layout.setMinimumHeight((int)(displayRectangle.height() * 0.9f));

dialog.setView(layout);

In general only adjusting the width should be sufficient in most cases.

Roter answered 6/6, 2012 at 10:3 Comment(2)
This doesn't seem to work completely on 4.0 and above. It does not fill 90% of the screen. Any idea why? I'm doing this on a Motorola Xoom with 4.0Koontz
@RyanGray It is working for me on a Samsung Nexus S with updated OS. Without additonal information I am unfortunately unable to help you.Roter
C
88

Set android:minWidth and android:minHeight in your custom view xml. These can force the alert not to just wrap content size. Using a view like this should do it:

<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:minWidth="300dp" 
  android:minHeight="400dp">
  <ImageView
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:background="@drawable/icon"/>
</LinearLayout>
Consol answered 22/2, 2010 at 2:52 Comment(9)
Yes with this I can set it to a specific size, but I want it to be screensize minus a padding of e.g. 20 pixel. Or width = 90% of screenwidth.Merryman
I density independent pixels are always scaled so that any screen is 320x480dp so a 300x460dp view would be a 20dp padding in all cases. Alternatively you could find the size of the screen like this: Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); int width = display.getWidth(); and set maxWidth and maxHeight accordingly.Consol
Hmm from the decoumentation I understand the concept of dp. But what if the screen ratio is 16:9 or 4:3? Will th dp be stretched unevenly?Merryman
No, the dp resolution will only be 320x480 if the screen ratio is 2:3, so this method will not work.Wanitawanneeickel
Actually, density independent pixels (dp) compensate for the screen pixel density so you can treat the resolution as 160 dpi. The dimension of the screen in dp will still depend on the physical screen size. See my "show resources" app and try it on a couple different-sized devices. You'll only see 320x480 if your screen is 2"x3". play.google.com/store/apps/details?id=org.efalk.showresourcesRanchero
300dp/400dp doesnt mean 90% of X screen.Cheek
This is very simple and easy solution to set width of dialogTamathatamaulipas
what, why is this answer upvoted so many times? this is a terrible solution since it has completely no regard to what device size the user is using.Batfish
used very well.Bevy
F
57
dialog.getWindow().setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
Filemon answered 24/1, 2012 at 18:13 Comment(3)
This worked for me and was easy to translate into MonoDroid which worked like so (where d is a new Dialog): d.Window.SetLayout(WindowManagerLayoutParams.FillParent, WindowManagerLayoutParams.FillParent);Pelfrey
But 90% is not the same as 100%. FILL_PARENT would indicate to fill the entire width, 100%, not 90%. Right?Murraymurre
@Murraymurre You are right. You can substitute FILL_PARENT with width computed as 90% of the current display's width. But I like the answer because it is easier than the others.Lemniscus
S
34

The following worked fine for me:

    <style name="MyAlertDialogTheme" parent="Base.Theme.AppCompat.Light.Dialog.Alert">
        <item name="windowFixedWidthMajor">90%</item>
        <item name="windowFixedWidthMinor">90%</item>
    </style>

(note: windowMinWidthMajor/Minor as suggested in previous answers didn't do the trick. My dialogs kept changing sizes depending on the content)

and then:

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.MyAlertDialogTheme);
Sices answered 3/2, 2016 at 12:15 Comment(3)
Best answer so far. Worked perfectly for me !Kleinstein
I wonder: how can I get the value of such special dimensions, which are set in percentage, via code?Ob
crazy I know but I had to use BOTH windowMinWidthMinor and android:windowMinWidthMinor variations for this to work across different android versions...Ana
P
30

All of the other answers here makes sense, but it did not meet what Fabian needs. Here is a solution of mine. It may not be the perfect solution but it works for me. It shows a dialog which is on fullscreen but you can specify a padding on top, bottom, left or right.

First put this in your res/values/styles.xml :

<style name="CustomDialog" parent="@android:style/Theme.Dialog">
    <item name="android:windowIsTranslucent">true</item>
    <item name="android:windowBackground">@color/Black0Percent</item>
    <item name="android:paddingTop">20dp</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:windowNoTitle">true</item>
    <item name="android:backgroundDimEnabled">false</item>
    <item name="android:windowIsFloating">false</item>
</style>

As you can see I have there android:paddingTop= 20dp is basically what you need. The android:windowBackground = @color/Black0Percent is just a color code declared on my color.xml

res/values/color.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="Black0Percent">#00000000</color>
</resources>

That Color code just serves as a dummy to replace the default window background of the Dialog with a 0% transparency color.

Next build the custom dialog layout res/layout/dialog.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/dialoglayout"
    android:layout_width="match_parent"
    android:background="@drawable/DesiredImageBackground"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/edittext1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:singleLine="true"
        android:textSize="18dp" />

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Dummy Button"
        android:textSize="18dp" />

</LinearLayout>

Finally here is our dialog that set custom view which uses our dialog.xml:

Dialog customDialog;
LayoutInflater inflater = (LayoutInflater) getLayoutInflater();
View customView = inflater.inflate(R.layout.dialog, null);
// Build the dialog
customDialog = new Dialog(this, R.style.CustomDialog);
customDialog.setContentView(customView);
customDialog.show();

Conclusion: I tried to override the dialog's theme in the styles.xml named CustomDialog. It overrides the Dialog window layout and gives me the chance to set a padding and change the opacity of the background. It may not be the perfect solution but I hope it helps you..:)

Poker answered 24/1, 2014 at 9:51 Comment(4)
it works for jellybean for now i've nt been able to test it other bulidsTlaxcala
Seems the cleanest and most elegant solution. Works on Kitkat 4.4 and 4.3.Various
I have a custom dialog, and NOTHING was working until I see this, the magic, ALL THE MAGIC on a custom dialog (that extends DialogFragment) comes when you do: Dialog customDialog = new Dialog(context, STYLE); thanks, REALLY, thanks.Shoshanashoshanna
This works like a charm for the dialog window! (you can also define a Black60Percent to have the original window greyed out) The unfortunate side effect is that all my views in the dialog inherited the paddings I set for the dialog....Statfarad
A
28

You can use percentage for (JUST) windows dialog width.

Look into this example from Holo Theme:

<style name="Theme.Holo.Dialog.NoActionBar.MinWidth">
    <item name="android:windowMinWidthMajor">@android:dimen/dialog_min_width_major</item>
    <item name="android:windowMinWidthMinor">@android:dimen/dialog_min_width_minor</item>
</style>

 <!-- The platform's desired minimum size for a dialog's width when it
     is along the major axis (that is the screen is landscape).  This may
     be either a fraction or a dimension. -->
<item type="dimen" name="dialog_min_width_major">65%</item>

All you need to do is extend this theme and change the values for "Major" and "Minor" to 90% instead 65%.

Regards.

Arndt answered 29/9, 2014 at 20:52 Comment(1)
To use this with dialog just pass your custom style in dialog builder constructor :)Herby
A
23

Solution with actual 90% calculation:

@Override public void onStart() {
   Dialog dialog = getDialog();
   if (dialog != null) {
     dialog.getWindow()
        .setLayout((int) (getScreenWidth(getActivity()) * .9), ViewGroup.LayoutParams.MATCH_PARENT);
   }
}

where getScreenWidth(Activity activity) is defined the following (best put in a Utils class):

public static int getScreenWidth(Activity activity) {
   Point size = new Point();
   activity.getWindowManager().getDefaultDisplay().getSize(size);
   return size.x;
}
Ahrens answered 15/6, 2016 at 11:47 Comment(6)
works like charm for an appcompatactivity that should function like dialogPoncho
I am getting array index out of bound on this :(Welldressed
@Dr.aNdRO how? Which line? Are you sure it's this piece of code and not smt else?Ahrens
.setLayout() I am getting at this line, When I change it to WRAP CONTENT this works fineWelldressed
See also: #36778084Provincial
@Provincial I'm sorry to say this but, your answer not only lacks a solution to the 90% problem presented on this question, neither is it "good" code - it's redundantAhrens
K
13

Get the device width:

public static int getWidth(Context context) {
    DisplayMetrics displayMetrics = new DisplayMetrics();
    WindowManager windowmanager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    windowmanager.getDefaultDisplay().getMetrics(displayMetrics);
    return displayMetrics.widthPixels;
}

then use that for making dialog 90% of device,

Dialog filterDialog = new Dialog(context, R.style.searchsdk_FilterDialog);

filterDialog.setContentView(R.layout.searchsdk_filter_popup);
initFilterDialog(filterDialog);
filterDialog.setCancelable(true);
filterDialog.getWindow().setLayout(((getWidth(context) / 100) * 90), LinearLayout.LayoutParams.MATCH_PARENT);
filterDialog.getWindow().setGravity(Gravity.END);
filterDialog.show();
Kancler answered 16/3, 2018 at 7:48 Comment(0)
I
9

By far the most simplest way I can think of -

If your dialog is made out of a vertical LinearLayout, just add a "height filling" dummy view, that will occupy the entire height of the screen.

For example -

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:orientation="vertical"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:weightSum="1">

    <EditText
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:id="@+id/editSearch" />

    <ListView
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:id="@+id/listView"/>


   <!-- this is a dummy view that will make sure the dialog is highest -->
   <View
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:layout_weight="1"/>

</LinearLayout>

Notice the android:weightSum="1" in the LinearLayout's attributes and the android:layout_weight="1" in the dummy View's attributes

Interosculate answered 8/6, 2015 at 15:32 Comment(1)
Nice! This keeps my webview from starting off extremely short and expanding to full height after onPageFinished. Kudos!Pompei
B
8

Well, you have to set your dialog's height and width before to show this ( dialog.show() )

so, do something like this:

dialog.getWindow().setLayout(width, height);

//then

dialog.show()
Buckeen answered 27/2, 2012 at 17:13 Comment(1)
Doesn't set dimensions for me. API >= 21.Tacket
D
7

Well, you have to set your dialog's height and width before to show this ( dialog.show() )

so, do something like this:

dialog.getWindow().setLayout(width, height);

//then

dialog.show()

Getting this code, i made it some changes:

dialog.getWindow().setLayout((int)(MapGeaGtaxiActivity.this.getWindow().peekDecorView().getWidth()*0.9),(int) (MapGeaGtaxiActivity.this.getWindow().peekDecorView().getHeight()*0.9));

however, dialog size's could change when the device change its position. Perhaps you need to handle by your own when metrics changes. PD: peekDecorView, implies that layout in activity is properly initialized otherwise you may use

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int height = metrics.heightPixels;
int wwidth = metrics.widthPixels;

in order to get screen size

Differentiable answered 14/2, 2013 at 22:29 Comment(0)
P
7

After initialize your dialog object and set the content view. Do this and enjoy.

(in the case i am setting 90% to width and 70% to height because width 90% it will be over toolbar )

DisplayMetrics displaymetrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int width = (int) ((int)displaymetrics.widthPixels * 0.9);
int height = (int) ((int)displaymetrics.heightPixels * 0.7);
d.getWindow().setLayout(width,height);
d.show();
Pneumatophore answered 17/4, 2016 at 13:55 Comment(0)
M
6
***In Kotlin You can Code like This : -*** 

fun customDialog(activity: Activity?, layout: Int): Dialog {
    val dialog = Dialog(activity!!)
    try {
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
        dialog.setCancelable(false)
        dialog.setContentView(layout)
        dialog.window!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        dialog.window!!.setLayout(ConstraintLayout.LayoutParams.MATCH_PARENT, ConstraintLayout.LayoutParams.WRAP_CONTENT);
        dialog.show()
    } catch (e: Exception) {

    }
    return dialog
}
Mackay answered 22/2, 2022 at 5:49 Comment(0)
C
5

Just give the AlertDialog this theme

<style name="DialogTheme" parent="Theme.MaterialComponents.Light.Dialog.MinWidth">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="android:windowMinWidthMajor">90%</item>
    <item name="android:windowMinWidthMinor">90%</item>
</style>
Covenanter answered 17/2, 2020 at 15:9 Comment(0)
S
4

My answer is based on the koma's but it doesn't require to override onStart but only onCreateView which is almost always overridden by default when you create new fragments.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.your_fragment_layout, container);

    Rect displayRectangle = new Rect();
    Window window = getDialog().getWindow();
    window.getDecorView().getWindowVisibleDisplayFrame(displayRectangle);

    v.setMinimumWidth((int)(displayRectangle.width() * 0.9f));
    v.setMinimumHeight((int)(displayRectangle.height() * 0.9f));

    return v;
}

I've tested it on Android 5.0.1.

Shantay answered 5/1, 2015 at 9:25 Comment(0)
B
4

Above many of the answers are good but none of the worked for me fully. So i combined the answer from @nmr and got this one.

final Dialog d = new Dialog(getActivity());
        //  d.getWindow().setBackgroundDrawable(R.color.action_bar_bg);
        d.requestWindowFeature(Window.FEATURE_NO_TITLE);
        d.setContentView(R.layout.dialog_box_shipment_detail);

        WindowManager wm = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE); // for activity use context instead of getActivity()
        Display display = wm.getDefaultDisplay(); // getting the screen size of device
        Point size = new Point();
        display.getSize(size);
        int width = size.x - 20;  // Set your heights
        int height = size.y - 80; // set your widths

        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        lp.copyFrom(d.getWindow().getAttributes());

        lp.width = width;
        lp.height = height;

        d.getWindow().setAttributes(lp);
        d.show();
Belinda answered 14/5, 2015 at 14:29 Comment(0)
H
4
    ...
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    Dialog d = builder.create(); //create Dialog
    d.show(); //first show

    DisplayMetrics metrics = new DisplayMetrics(); //get metrics of screen
    getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
    int height = (int) (metrics.heightPixels*0.9); //set height to 90% of total
    int width = (int) (metrics.widthPixels*0.9); //set width to 90% of total

    d.getWindow().setLayout(width, height); //set layout
Hustler answered 3/2, 2016 at 7:7 Comment(1)
showing the dialog before setting layout works for me.Paulie
R
4

You need to use a style @style.xml such as CustomDialog to displaying the customize-able dialog.

<style name="CustomDialog" parent="@android:style/Theme.DeviceDefault.Light.Dialog">
    <item name="android:windowIsTranslucent">true</item>
    <item name="android:windowBackground">@color/colorWhite</item>
    <item name="android:editTextColor">@color/colorBlack</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:windowNoTitle">true</item>
    <item name="android:backgroundDimEnabled">true</item>
    <item name="android:windowIsFloating">true</item>
    <item name="android:windowSoftInputMode">stateUnspecified|adjustPan</item>
</style>

and use this style in Activity.java like this

Dialog dialog = new Dialog(Activity.this, R.style.CustomDialog);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.custom_dialog);

and your custom_dialog.xml should inside your layout directory

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="10dp"
    android:paddingRight="10dp">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text=""
        android:textSize="20dp"
        android:id="@+id/tittle_text_view"
        android:textColor="@color/colorBlack"
        android:layout_marginTop="20dp"
        android:layout_marginLeft="10dp"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginLeft="20dp"
        android:layout_marginBottom="10dp"
        android:layout_marginTop="20dp"
        android:layout_marginRight="20dp">

        <EditText
            android:id="@+id/edit_text_first"
            android:layout_width="50dp"
            android:layout_height="match_parent"
            android:hint="0"
            android:inputType="number" />

        <TextView
            android:id="@+id/text_view_first"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginLeft="5dp"
            android:gravity="center"/>

        <EditText
            android:id="@+id/edit_text_second"
            android:layout_width="50dp"
            android:layout_height="match_parent"
            android:hint="0"
            android:layout_marginLeft="5dp"
            android:inputType="number" />

        <TextView
            android:id="@+id/text_view_second"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginLeft="5dp"
            android:gravity="center"/>

    </LinearLayout>

</LinearLayout>
Rephrase answered 28/3, 2018 at 11:15 Comment(0)
D
3

Here is my variant for custom dialog's width:

DisplayMetrics displaymetrics = new DisplayMetrics();
mActivity.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int width = (int) (displaymetrics.widthPixels * (ThemeHelper.isPortrait(mContext) ? 0.95 : 0.65));

WindowManager.LayoutParams params = getWindow().getAttributes();
params.width = width;
getWindow().setAttributes(params);

So depending on device orientation (ThemeHelper.isPortrait(mContext)) dialog's width will be either 95% (for portrait mode) or 65% (for landscape). It's a little more that the author asked but it could be useful to someone.

You need to create a class that extends from Dialog and put this code into your onCreate(Bundle savedInstanceState) method.

For dialog's height the code should be similar to this.

Ducan answered 24/5, 2013 at 8:20 Comment(3)
What is ThemeHelper? I don't have this class available in my project.Erotomania
ThemeHelper is just a helper class for my needs. Its method isPortrait(Context) returns whether the device's screen orientation is portrait or landscape.Ducan
this will have issue if once dialog loaded and then we change the orientation, it will keep its initial setting in onCreateSlob
E
3
public static WindowManager.LayoutParams setDialogLayoutParams(Activity activity, Dialog dialog)
    {
        try 
        {
            Display display = activity.getWindowManager().getDefaultDisplay();
            Point screenSize = new Point();
            display.getSize(screenSize);
            int width = screenSize.x;

            WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
            layoutParams.copyFrom(dialog.getWindow().getAttributes());
            layoutParams.width = (int) (width - (width * 0.07) ); 
            layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
            return layoutParams;
        } 
        catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }
    }
Eyespot answered 2/9, 2013 at 10:44 Comment(0)
D
3

If you use dialog fragment you can do it on onResume method. It's code for Xamarin Android, but I think it so easy to understand it

public override void OnResume() 
{
    base.OnResume();
    var metrics = Resources.DisplayMetrics;

    double width = metrics.WidthPixels * 0.9;
    double height = metrics.HeightPixels * 0.6;

    this.Dialog.Window.SetLayout((int)width, (int)height);
    this.Dialog.Window.SetGravity(Android.Views.GravityFlags.Center);
}
Derange answered 27/8, 2020 at 8:44 Comment(0)
N
3

Based in part on Anand's answer. This works for me:

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
    val fragmentActivity = requireActivity()
    val v = View.inflate(context, R.layout.fragment_about_dialog, null)
    val dialog = Dialog(fragmentActivity)
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
    dialog.setContentView(v)

    val wm = fragmentActivity.getSystemService(Context.WINDOW_SERVICE) as WindowManager 

    val display = if (VERSION.SDK_INT >= VERSION_CODES.R) {
        fragmentActivity.display
    } else {
        wm.defaultDisplay // deprecated in API 30
    }

    val size = Point()
    display?.getSize(size)

    val width = size.x - 50
    val height = size.y - 50
    val lp = WindowManager.LayoutParams()
    lp.copyFrom(dialog.window?.attributes)
    lp.width = width
    lp.height = height
    dialog.show()
    dialog.window?.attributes = lp
    
    return dialog
}

For dialog layout used constraintLayout:

<androidx.constraintlayout.widget.ConstraintLayout 
        android:id="@+id/dialogLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    ...
</androidx.constraintlayout.widget.ConstraintLayout>

Result:

enter image description here

This works fine when changing screen orientation.

Nauplius answered 2/9, 2020 at 8:47 Comment(0)
T
2

Here is a short answer that worked for me (Tested on API 8 and API 19).

Dialog mDialog;
View   mDialogView;
...
// Get height
int height = mDialog.getWindow()
.getWindowManager().getDefaultDisplay()
.getHeight();

// Set your desired padding (here 90%)
int padding = height - (int)(height*0.9f);

// Apply it to the Dialog
mDialogView.setPadding(
// padding left
0,
// padding top (90%)
padding, 
// padding right
0, 
// padding bottom (90%)
padding);
Towelling answered 19/11, 2014 at 11:8 Comment(0)
B
2

If you are using Constraint Layout, you can set any view inside it, to fill a percentage of the screen with:

layout_constraintWidth_percent="0.8"

So, for example, if you have a ScrollView inside the dialog and you want to set it to a percentage of the screen height. It would be like this:

<ScrollView
            android:id="@+id/scrollView"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            app:layout_constraintHeight_percent="0.8">

Hope it helps someone !!

Bolshevism answered 14/10, 2019 at 18:30 Comment(0)
H
2

Make your dialog an activity. 3 Steps

STEP 1: Put one of these in styles.xml

Style One: I like this one because you can change the parent theme to the name of your theme that you are using for the rest of your app.

<style name="DialogTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:windowIsTranslucent">true</item>
    <item name="android:windowBackground">@color/transparent</item>
    <item name="android:windowIsFloating">true</item>
    <item name="android:windowMinWidthMajor">90%</item>
    <item name="android:windowMinWidthMinor">90%</item>
</style>

Style Two:

<style name="DialogTheme" parent="Theme.AppCompat.Dialog">
    <item name="android:windowMinWidthMajor">90%</item>
    <item name="android:windowMinWidthMinor">90%</item>
</style>

STEP 2: Then put this in AndroidManifest.xml

<activity
    android:name="com.example.YourApp.DialogActivity"
    android:theme="@style/DialogTheme" />

STEP 3: And make sure you have your main layout width fill_parent or match_parent in activity_dialog.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    tools:context=".DialogActivity">

</androidx.constraintlayout.widget.ConstraintLayout>
Hindorff answered 2/3, 2021 at 22:33 Comment(0)
A
1
    final AlertDialog alertDialog;

    LayoutInflater li = LayoutInflater.from(mActivity);
    final View promptsView = li.inflate(R.layout.layout_dialog_select_time, null);

    RecyclerView recyclerViewTime;
    RippleButton buttonDone;

    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mActivity);
    alertDialogBuilder.setView(promptsView);

    // create alert dialog
    alertDialog = alertDialogBuilder.create();

    /**
     * setting up window design
     */
    alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);


    alertDialog.show();

    DisplayMetrics metrics = new DisplayMetrics(); //get metrics of screen
    mActivity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
    int height = (int) (metrics.heightPixels * 0.9); //set height to 90% of total
    int width = (int) (metrics.widthPixels * 0.9); //set width to 90% of total

    alertDialog.getWindow().setLayout(width, height); //set layout
    recyclerViewTime = promptsView.findViewById(R.id.recyclerViewTime);


    DialogSelectTimeAdapter dialogSelectTimeAdapter = new DialogSelectTimeAdapter(this);
    RecyclerView.LayoutManager linearLayoutManager = new LinearLayoutManager(this);
    recyclerViewTime.setLayoutManager(linearLayoutManager);
    recyclerViewTime.setAdapter(dialogSelectTimeAdapter);

    buttonDone = promptsView.findViewById(R.id.buttonDone);
    buttonDone.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            alertDialog.dismiss();

        }
    });
Asyut answered 5/3, 2018 at 4:55 Comment(1)
custom dialog with the dialog custom heightAsyut
S
1

I found very simple and easy to use a workaround

    fun showDialog(){
    val dialog = Dialog(this@DialogActivity)
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
    dialog.setCancelable(false)
    dialog.setContentView(R.layout.custom_dialog)
    val txtTitle = dialog.findViewById<TextView>(R.id.txtTitle)
    val btn  = dialog.findViewById<Button>(R.id.button)

    btn.setOnClickListener {
        Toast.makeText(this,"test",Toast.LENGTH_SHORT).show()
    }
    txtTitle.setText("ali")
    dialog.show()

    val window = dialog.window
    window?.setLayout(WindowManager.LayoutParams.MATCH_PARENT,WindowManager.LayoutParams.WRAP_CONTENT)
}
Supermundane answered 10/2, 2022 at 17:27 Comment(0)
P
0
dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT,WindowManager.LayoutParams.WRAP_CONTENT);
Pulque answered 19/7, 2017 at 16:35 Comment(0)
F
0

Method 1: Dialog extension:

fun Dialog.setWidthPercent(percentage: Int = 80) {
    val percent = percentage.toFloat() / 100
    val dm = Resources.getSystem().displayMetrics
    val rect = dm.run { Rect(0, 0, widthPixels, heightPixels) }
    val percentWidth = rect.width() * percent
    window?.setLayout(percentWidth.toInt(), ViewGroup.LayoutParams.WRAP_CONTENT)
}

Method 2: Using theme

Theme.xml

<style name="DialogTheme" parent="Theme.AppCompat.Dialog">
    <item name="android:windowMinWidthMajor">90%</item>
    <item name="android:windowMinWidthMinor">90%</item>
</style>

In your Activity or fragment

   /* if you want to add theme....
    val dialog = Dialog(this,R.style.Theme_Dialog) 
     */
    val dialog = Dialog(this)
    val dialogBinding = DialogAddTextBinding.inflate(layoutInflater)
    dialog.apply {
        window!!.requestFeature(Window.FEATURE_NO_TITLE)
        setContentView(dialogBinding.root)
        show()
        // call set setWidthPercent
        setWidthPercent()
        setCancelable(false)
        window!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        setOnDismissListener {
           
        }
    }
    dialogBinding.apply {
// add your listeners here....
    }
Fordo answered 20/5, 2023 at 5:47 Comment(0)
S
0

There is a great solution specially if you want height to be dynamic according to content. If height is too much and cant fit to screen, then screen will be set to highest height possible and content will be scrollable.

First wrap your xml content with scroll view. Second set android:fitsSystemWindows="true" for scroll view. Root layout's height should be wrap_content It is possible to give padding/margin to dialog

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginVertical="24dp"
        android:fitsSystemWindows="true">

        .... your scrollable content

         
    </ScrollView>
</FrameLayout>

If you wanna do the exact %X of the screen try something like this with guide lines.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guidelineStart"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.05" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guildelineEnd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.95" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
       app:layout_constraintTop_toBottomOf="@id/guidelineStart"
        app:layout_constraintBottom_toTopOf="@id/guildelineEnd"
        android:background="@drawable/default_dialog_bg"
        app:layout_constrainedHeight="true"
        android:fitsSystemWindows="true">

        .... your scrollable content
        
    </ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>

thanks to @ibrahim.menekse

Shauna answered 25/1 at 12:41 Comment(0)
R
-1

Try this:

dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
Resident answered 20/7, 2020 at 14:21 Comment(1)
The OP asks for 90%, not full screenMonah

© 2022 - 2024 — McMap. All rights reserved.