0

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?

Community
  • 1
  • 1
Rishab Jaiswal
  • 349
  • 3
  • 19

2 Answers2

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);
Mrinmoy
  • 1,370
  • 2
  • 18
  • 28
0

Replace below code:

dialog.getWindow().setLayout(getResources().getDimensionPixelSize(R.dimen.layout_height_400dp), WindowManager.LayoutParams.MATCH_PARENT); 
Mavya Soni
  • 932
  • 7
  • 15