Get width of AlertDialog in pixels or dp

454
December 23, 2016, at 5:41 PM

I was trying to get the width of an AlertDialog in Pixels and also set its width dynamically.

 getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
 int width = displaymetrics.widthPixels;
 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
 lp.copyFrom(dialog.getWindow().getAttributes());
 lp.width = width;
 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
 lp.gravity = Gravity.CENTER;
 dialog.getWindow().setAttributes(lp);

The above code didn't work for me. Also, I followed other codes too like here but none helped.

How can I get and set width of AlertDialog in pixels or dp?

Answer 1

you can only get widht and height of view, So if its custom dialog, take its root view kindly follow the example

RelativeLayout rl = (RelativeLayout) dialog.findViewById(R.id.root_relative_layout);

Here relative layout is the parent view and component are in it.

Now to get height and width do this:-

int width = rl.getWidth();
int height = rl.getHeight();

To set widht and height do this

 AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setView(layout);
    builder.setTitle("Title");
    alertDialog = builder.create();
    alertDialog.getWindow().setLayout(600, 400); //Controlling width and height.
    alertDialog.show();

OR

WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(alertDialog.getWindow().getAttributes());
lp.width = 150;
lp.height = 500;
lp.x=-170;
lp.y=100;
alertDialog.getWindow().setAttributes(lp);
Answer 2

Replace below code:

dialog.getWindow().setLayout(getResources().getDimensionPixelSize(R.dimen.layout_height_400dp), WindowManager.LayoutParams.MATCH_PARENT); 
Rent Charter Buses Company
READ ALSO
What is m2repository folder in local android SDK?

What is m2repository folder in local android SDK?

I was trying to look for a list of version for android support library, and finally i found m2repository and support folders in android folderWhat is that?

422
FCM Notification onclick does not open desired activity

FCM Notification onclick does not open desired activity

i have tried almost every solution posted here and combination of every flag but it is not working

856
Can I not use the Android crop intent to create a cropping tool like WhatsApp?

Can I not use the Android crop intent to create a cropping tool like WhatsApp?

I am creating an Android application that has image upload facility, but I need to reduce the size of the image without losing its qualityI tried out the Android intent in all possible ways, but I am not getting the desired output

375