3

I am developing an Android app. In my app, I am trying to show an alert dialog setting custom view. Setting custom view is ok. But I am having problem with setting the width of my dialog. I cannot set the width. It is always default with.

This is how I show dialog

AlertDialog.Builder builder = new AlertDialog.Builder(context);
            View view = layoutInflater.inflate(R.layout.meme_post_actions_dialog,null);
            builder.setView(view);
            builder.create().show();

This is xml layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:gravity="center"
    android:orientation="vertical" android:layout_width="100dp"
    android:layout_height="match_parent">
    <TextView
        android:text="This is dialog"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

As you can see I set the width to 100dp. So it width will be too small. But this is what I got.

enter image description here

How can I set the width of the custom alert dialog?

halfer
  • 19,824
  • 17
  • 99
  • 186
Wai Yan Hein
  • 13,651
  • 35
  • 180
  • 372
  • Hi,@ Wai Yan Hein try to this link hope this can help you.http://stackoverflow.com/questions/12478520/how-to-set-dialogfragments-width-and-height – Dileep Patel Oct 15 '16 at 05:57

2 Answers2

3

There might be the number of ways you can control it. Let me share with you one of the approaches by setting alert window width and height.

AlertDialog.Builder builder = new AlertDialog.Builder(this);
View view = layoutInflater.inflate(R.layout.meme_post_actions_dialog,null);
        builder.setView(view);
builder.setView(layout);
alertDialog = builder.create();
alertDialog.show();
alertDialog.getWindow().setLayout(600, 400); //<--Controlling width and height.

In last make sure that parent of your layout should match parent.

android:layout_width="match_parent"
android:layout_height="match_parent"
Bhavdip Sagar
  • 1,951
  • 15
  • 27
2

Try this :

AlertDialog.Builder builder = new AlertDialog.Builder(context);
            View view = layoutInflater.inflate(R.layout.meme_post_actions_dialog,null);
            builder.setView(view);
int width = (int)(getResources().getDisplayMetrics().widthPixels*0.50); //<-- int width=400;
int height = (int)(getResources().getDisplayMetrics().heightPixels*0.50);//<-- int height =300;
AlertDialog alertDialog = builder.create();
alertDialog.getWindow().setLayout(width, height);
Ahmad Aghazadeh
  • 16,571
  • 12
  • 101
  • 98