I want the dialog doesn't stretch to fit width of display screen. I want the dialog had about 90% of screen width and center its.
How can I do it?
Thank you very much ^^
You can give style with below attributes to get dialog size as percentage of screen.
<style name="YourDialogTheme">
<item name="android:windowMinWidthMajor">90%</item>
<item name="android:windowMinWidthMinor">90%</item>
</style>
Then Apply theme as below in your dialog:
AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.YourDialogTheme));
See windowMinWidthMinor
and windowMinWidthMajor
For the easiest way you can do something like this:
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="#dimen/defaultMargin"
android:paddingRight="#dimen/defaultMargin">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</RelativeLayout>
also, this link can referred
Here is the example to set margins in dialogs
final Dialog dialog = new Dialog(context);
// ...
// e.g. top + right margins:
dialog.getWindow().setGravity(Gravity.TOP|Gravity.RIGHT);
WindowManager.LayoutParams layoutParams = dialog.getWindow().getAttributes();
layoutParams.x = 100; // right margin
layoutParams.y = 170; // top margin
dialog.getWindow().setAttributes(layoutParams);
// e.g. bottom + left margins:
dialog.getWindow().setGravity(Gravity.BOTTOM|Gravity.LEFT);
WindowManager.LayoutParams layoutParams = dialog.getWindow().getAttributes();
layoutParams.x = 100; // left margin
layoutParams.y = 170; // bottom margin
dialog.getWindow().setAttributes(layoutParams);
Currently, I have the following dialog, which I will perform expand/ collapse animation on its items.
This dialog is created via the following code
import android.support.v7.app.AlertDialog;
final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
final AlertDialog dialog = builder.setView(view).create();
final ViewTreeObserver vto = view.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
public void onGlobalLayout() {
ViewTreeObserver obs = view.getViewTreeObserver();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
obs.removeOnGlobalLayoutListener(this);
} else {
obs.removeGlobalOnLayoutListener(this);
}
// http://stackoverflow.com/questions/19326142/why-listview-expand-collapse-animation-appears-much-slower-in-dialogfragment-tha
int width = dialog.getWindow().getDecorView().getWidth();
int height = dialog.getWindow().getDecorView().getHeight();
dialog.getWindow().setLayout(width, height);
}
});
However, when animation being performed, here's the side effect.
Note, the unwanted extra white region at the dialog after animation, is not caused by our custom view. It is the system window white background of the dialog itself.
I tend to make the system window background of the dialog, to become transparent.
final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
final AlertDialog dialog = builder.setView(view).create();
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
Although the unwanted white background is no longer seen, the original margin of the dialog is gone too. (The dialog width is now full screen width)
How can I make it transparent, without affecting its margin?
There's a pretty easy way to do that:
You need to "modify" the Drawable that is being used as a background of the Dialog. Those sort of Dialogs use an InsetDrawable as a background.
API >= 23
Only SDK API 23+ allows you to get the source Drawable wrapped by the InsetDrawable (getDrawable() method). With this, you can do whatever you want - e.g. change color to something completely different (like RED or something). If you use this approach remember that the wrapped Drawable is a GradientDrawable and not a ColorDrawable!
API < 23
For lower APIs your ("elegant") options are very limited.
Fortunately you don't need to change the color to some crazy value, you just need to change it to TRANSPARENT. For this you can use setAlpha(...) method on InsetDrawable.
InsetDrawable background =
(InsetDrawable) dialog.getWindow().getDecorView().getBackground();
background.setAlpha(0);
EDIT (as a result of Cheok Yan Cheng's comments):
or you can actually skip casting to InsetDrawable and get the same result. Just remember that doing so will cause the alpha to be changed on the InsetDrawable itself and not on the Drawable that is wrapped by the InsetDrawable.
Try to below Theme:
<style name="TransaparantDialog">
<item name="android:windowBackground">#android:color/transparent</item>
<item name="android:windowFrame">#null</item>
<item name="android:windowTitleStyle">#null</item>
<item name="android:windowIsFloating">true</item>
<item name="android:windowAnimationStyle">#android:style/Animation.Dialog</item>
<item name="android:windowContentOverlay">#null</item>
<item name="android:backgroundDimEnabled">false</item>
<item name="android:background">#android:color/transparent</item>
<item name="android:windowSoftInputMode">stateUnspecified|adjustPan</item>
</style>
Try below code to apply Theme to AlertDialog.Builder:
final AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(activity, R.style.TransaparantDialog));
...
dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
I hope help you !
The background image abc_popup_background_mtrl_mult which is part of the compat library contains already a margin in the picture information.
This is why the margin goes away when you remove the background image. I strongly recommend not to use the ViewTreeObserver, it will been called multiple times and can cause performance issues. Better work with the screen size:
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
Your problem is properly in the layout try to check the views with the Hierarchy viewer.
just add this line after show dialog. I would prefer using Dialog instedof using AlertDialog
dialog.getWindow().setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
Let's start with Google recommendation which says to use DialogFragment instead of a simple Dialog.
#rekire is right that margins set by drawable, going forward it is set by either 9 patch or programmatically depending on theme.
So you either can set your padding to your content view or create dialog using DialogFragment here is an example which changes height of dialog based on it's content, and note you don't need to use tree observer which is as mentioned before may cause performance issue.
So the example
dialog_confirm.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="20dp">
<LinearLayout android:id="#+id/container"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/white"
android:orientation="vertical"
android:animateLayoutChanges="true"
android:padding="15dp">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:padding="10dp"
android:text="A label text"
android:textAppearance="?android:attr/textAppearanceLarge"/>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:padding="10dp"
android:text="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque mauris mi, dictum a lectus ut, facilisis"
android:textAppearance="?android:attr/textAppearanceMedium"/>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Remove Me"/>
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Remove Me"/>
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Remove Me"/>
<!-- as much content as you need -->
</LinearLayout>
</ScrollView>
Note: I wrapped everything into scroll view and set padding you can skip it if you want.
ConfirmDialog.java
//here goes package name and imports
/**
* Created by Vilen - virtoos.com;
* fragment dialog example
*/
public class ConfirmDialog extends DialogFragment implements View.OnClickListener {
private Button button1;
private Button button2;
private Button button3;
private LinearLayout containerLayout;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NO_TITLE, 0);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.dialog_confirm, container, false);
containerLayout = (LinearLayout)v.findViewById(R.id.container);
button1 = (Button)v.findViewById(R.id.button1);
button2 = (Button)v.findViewById(R.id.button2);
button3 = (Button)v.findViewById(R.id.button3);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// make background transparent if you want
//getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return super.onCreateDialog(savedInstanceState);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.button1:
containerLayout.removeView(button1);
break;
case R.id.button2:
containerLayout.removeView(button2);
break;
case R.id.button3:
containerLayout.removeView(button3);
break;
}
}
}
and finally you can show your dialog with this piece of code
ConfirmDialog confirmDialog = new ConfirmDialog();
confirmDialog.show(getSupportFragmentManager(), "dialog");
I will not go into details why Fragment dialog is better but one thing is clear that you can encapsulate logic for it and have separate class.
Hope this solves your issue.
What should be there is what you didn't show, I'm not sure it is something you didn't know or it is already there so you don't think it is necessary to show.
Set theme to Dialog, that puts entire activity as one Dialog. I don't think you did it, otherwise AlertDialog would not be there.
I'm a bit lost your description, but there is that little <shape/> XML that is much more powerful then a 9-patch, and use RelativeLayout will help.
I want to set the width of custom dialog to wrap content
but always it fill all the width of the screen
I have tested this
android.view.WindowManager.LayoutParams params = mydialog.getWindow().getAttributes();
params.width = android.view.WindowManager.LayoutParams.WRAP_CONTENT;
mydialog.getWindow().setAttributes((android.view.WindowManager.LayoutParams) params);
and that
mydialog.getWindow().setLayout(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
I also having a hard time in solving this problem and finally got a better way in solving this.
Here is the workaround. In your code
mydialog.getWindow().setLayout(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
This is not working because the default layout for ProgressDialog has match_parent with margins left and right. To resize the ProgressDialog you need a Custom View like below:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#android:drawable/dialog_holo_light_frame"
android:layout_gravity="center_horizontal"
android:id="#+id/container"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ProgressBar
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp"
android:layout_marginLeft="30dp"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/progressBar"/>
<TextView
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp"
android:layout_marginRight="30dp"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="20dp"
android:gravity="center"
android:id="#+id/message"/>
</LinearLayout>
and inflate it after showing the ProgressDialog. After inflating the custom view, get the width of the custom view by using the GlobalLayoutListener and set the layout width.
mDialog.show();
final Window window = mDialog.getWindow();
window.setContentView(R.layout.custom_progress_dialog); // this is the above code
final LinearLayout dialogContainer = (LinearLayout) window.findViewById(R.id.container);
TextView message = (TextView) window.findViewById(R.id.message);
message.setText("Loading . . .");
dialogContainer.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
int width = dialogContainer.getWidth();
window.setLayout(width, WindowManager.LayoutParams.WRAP_CONTENT);
dialogContainer.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
});
I know this question is old, but if someone doesn't want to add WindowManager.LayoutParams then just set theme of the dialog to android.R.style.Theme_Holo_Light_Dialog_NoActionBar this will make the dialog to wrap it's width to its contents.
Example:
AlertDialog alert = new AlertDialog.Builder(context, android.R.style.Theme_Holo_Light_Dialog_NoActionBar).create();
Make sure that the layout you are inflating is set to wrap_content for both height and width.
Did you try using this
mydialog.getWindow().setLayout(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
after writing mydialog.show()?
That should work.
Try below code to have a dialog with wrap content.
(In dialogs layout xml use layout_width= WRAP_PATENT and height as WRAP_CONTENT)
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(dialog.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
dialog.show();
dialog.getWindow().setAttributes(lp);
set style to custom dialog with following attribute:
<style name="CustomDialogTheme" parent="#android:style/Theme.Dialog">
<item name="android:windowIsFloating">false</item>
</style>
I am creating a dialog to zoom in on an image,
However, my content is 240px and I would like to resize it to the screen width, to "fill_parent". Could you tell me what's wrong here? My picture stays small, 240px, not 480px.
final Dialog dialog = new Dialog(myview);
dialog.setContentView(R.layout.zoom);
dialog.setTitle(""+passInfoNom+" ");
imgView2 = (ImageView)dialog.findViewById(R.id.ImageZoom);
imgView2.setImageDrawable(image);
dialog.show();
Layout:
<?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:background="#ffffffff"
>
<ImageView android:id="#+id/ImageZoom"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</ImageView>
</LinearLayout>
It looks like you have set the content to "fill_parent" but you have not set the size of the dialog to be "fill_parent." change that and you should see some results.
But i have a question: if you want the zoom dialog to take up the whole screen, why dont you start a new activity, or crop the image and set the cropped portion as the content? it seems weird to me that you would zoom in a dialog. Google maps, for example, just zooms in the existing View.
As specified in another anwser, I am adjusting the size of my dialog by creating my own Dialog class and setting its size:
public class ZoomZoom extends Dialog
{
public ZoomZoom(Context context) {
super(context);
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.zoom);
LayoutParams params = getWindow().getAttributes();
params.width = LayoutParams.FILL_PARENT;
//params.height = LayoutParams.FILL_PARENT;
params.height = screenLargeur;
getWindow().setAttributes((android.view.WindowManager.LayoutParams) params);
imgView2 = (ImageView)findViewById(R.id.ImageZoom);
imgView2.setImageDrawable(imageZ);
imgView2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.hide();
}
});
}
}
Not sure if this has been resolved for you but you can also use android:minWidth and android:minHeight, setting them to by dip. For instance:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/send_chat_layout"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:background="#292929"
android:minWidth="300dip"
android:minHeight="400dip">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
From my understanding, due to the way Android scales in resolution, with a 360x480 screen, setting the mins to 340x460 will keep its aspect to larger resolutions.
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.
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 )
Try wrapping your custom dialog layout into RelativeLayout instead of LinearLayout. That worked for me.
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);
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.
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>
dialog.getWindow().setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
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);
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..:)
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.
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;
}
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();
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()
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
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
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();
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>
***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
}
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.
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();
...
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
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.
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;
}
}
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>
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:
This works fine when changing screen orientation.
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);
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 !!
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);
}
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>
dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT,WindowManager.LayoutParams.WRAP_CONTENT);
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();
}
});