Reputation: 14791
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.
How can I set the width of the custom alert dialog?
Upvotes: 3
Views: 4987
Reputation: 17131
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);
Upvotes: 2
Reputation: 1971
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"
Upvotes: 3