35

When I use in layout, which specifies this dialog android:layout_width="match_parent" I get this dialog:

small dialog

I need dialog which will be wider. Any ideas?

west44
  • 747
  • 3
  • 12
  • 24

2 Answers2

122

You can do that by grabbing the Window object that the dialog uses, and resetting the width. Here's a simple example:

//show the dialog first
AlertDialog dialog = new AlertDialog.Builder(this)
        .setTitle("Test Dialog")
        .setMessage("This should expand to the full width")
        .show();
//Grab the window of the dialog, and change the width
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
Window window = dialog.getWindow();
lp.copyFrom(window.getAttributes());
//This makes the dialog take up the full width
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
window.setAttributes(lp);

Here's the end result. Note that there's a lot more styling you can do to the dialog if you need to fine tune things (like change the background, etc). When I've had to do this in the past, I usually use this method, and customize the layout used in the dialog with setView() on the builder class.

example

wsanville
  • 37,158
  • 8
  • 76
  • 101
  • 2
    Just keep in mind that this might look strange on a large screen, like a tablet for example. – wsanville Jul 23 '12 at 15:28
  • 1
    What if my class extends Application and i want to call alertdialog in that? – ManishSB Dec 20 '14 at 13:17
  • 1
    If using a DialogFragment the setting must be done in the `onStart` method, see http://stackoverflow.com/questions/23990726/how-to-make-dialogfragment-width-to-fill-parent/26207535 – Eborbob Jul 02 '15 at 21:24
  • Setting the width to MATCH_PARENT does not completely stretch the dialog to the edges of the screen. There is a background to the window that has a bit of width, but is just set to transparent. I'd like to make the actual content area reach the edges of the screen. – h_k Jul 23 '15 at 19:58
  • 5
    one question: why is this such a damn pain-in-the-ass to do in the first place? If the outer layout of the XML states "match_parent" then it should be exactly THAT ! damn it, Google. – Someone Somewhere Sep 30 '15 at 12:30
  • 6
    @h_k You can remove those edges calling `dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));` – Juan José Melero Gómez Jan 21 '16 at 12:43
  • 1
    A supplyment is `window.setAttributes(lp);` should place after `dialog.show();`, or it won't work. – Zhuang Ma Jun 20 '16 at 08:06
4

Another way to fix this is to use:

import android.support.v7.app.AlertDialog;

instead of:

import android.app.AlertDialog;
user2880229
  • 151
  • 8