Search code examples
androidandroid-alertdialogandroid-progressbarlayoutparamsandroid-windowmanager

Android - How to make an AlertDialog narrower than standard?


I currently have the following code to build a wait dialog with a ProgressBar:

LayoutInflater factory = LayoutInflater.from(TherapistActivity.this);
View view = factory.inflate(R.layout.waitdialog, null);
dialog = new AlertDialog.Builder(TherapistActivity.this)
    .setView(view)
    .setCancelable(false)
    .create();
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
WindowManager.LayoutParams wmlp = dialog.getWindow().getAttributes();

wmlp.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
wmlp.x = 0;   //x position
wmlp.y = Math.round(metrics.density * 100);   //y position

wmlp.width = Math.round(metrics.density * 55);  //doesn't appear to work

Here is the XML for my dialog:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:id="@+id/top"
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="55dp"
            android:layout_height="55dp"
            android:background="@drawable/boxbkg">

<ProgressBar
    android:id="@+id/progressBar"
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"/>


</RelativeLayout>

I would like my dialog to be a small square dialog with just a spinning ProgressBar. However, even with wmlp.width = Math.round(metrics.density * 55), the dialog remains wide.

What is the proper way to get around this?


Solution

  • I figured it out. It appears that I needed two more lines of code. Before setting the width, I needed this line of code:

    wmlp.copyFrom(dialog.getWindow().getAttributes());
    

    And after setting the width, I needed this line of code:

    dialog.getWindow().setAttributes(wmlp);