簡體   English   中英

無法在Android中設置自定義對話框的寬度

[英]Unable to set the width of custom dialog in Android

我正在開發一款Android應用。 在我的應用程序中,我正在嘗試顯示設置自定義視圖的警報對話框。 設置自定義視圖是可以的。 但是我在設置對話框的寬度方面遇到了問題。 我無法設置寬度。 它始終默認為。

這是我顯示對話框的方式

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

這是xml布局

<?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>

如您所見,我將寬度設置為100dp。 所以寬度太小了。 但這就是我得到的。

在此輸入圖像描述

如何設置自定義警報對話框的寬度?

嘗試這個 :

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);

可能有多種方法可以控制它。 讓我通過設置警報窗口寬度和高度與您分享其中一種方法。

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.

最后確保布局的父級應與父級匹配。

android:layout_width="match_parent"
android:layout_height="match_parent"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM