2016-10-15 176 views
1

我正在開發一個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。所以它的寬度會太小。但這就是我得到的。

enter image description here

如何設置自定義警告對話框的寬度是多少?

+0

嗨,@惠燕黑嗯嘗試這個鏈接,希望這可以幫助you.http://stackoverflow.com/questions/12478520/how-to-set- dialogfragments-width-and-height –

回答

0

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

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" 
+0

謝謝。這工作。非常感謝。 :) –

+0

但如何設置wrap_content? –

+0

我的意思是alertDialog.getWindow()。setLayout(600,WRAP_CONTENT); –

2

試試這個:

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

NO。不工作。一樣。 –