不知道你們試過了嗎,AlertDialog在我們給他設置我們自己的布局的時候他的寬度不論我們怎么設置他都是不變的,要想改變寬和高我們可以動態的去修改他的寬度好高度
直接上代碼
// 1. 布局文件轉換為View對象 LayoutInflater inflater = LayoutInflater.from(context); RelativeLayout layout = (RelativeLayout) inflater.inflate(R.layout.mydialog_layout, null); // 2. 新建對話框對象 final AlertDialog.Builder builder = new AlertDialog.Builder(context,R.style.AlertDialog); //通過setView設置我們自己的布局 builder.setView(layout); final AlertDialog dialog =builder.create(); dialog.show(); //此處設置位置窗體大小 dialog.getWindow().setLayout(DensityUtil.dip2px(context,300), LinearLayout.LayoutParams.WRAP_CONTENT);
- 上面代碼通過AlertDialog.Builder的setView()方法設置我們自己的布局
- 通過builder.create()獲取AlertDialog對象,然后通過AlertDialog的etWindow().setLayout(DensityUtil.dip2px(context,300), LinearLayout.LayoutParams.WRAP_CONTENT);設置AlertDialog的寬和高
- DensityUtil.dip2px是dp轉px的工具類
- 在創建AlertDialog.Builder對象的時候我們有傳入兩個參數一個是Context另一個就是AlertDialog的樣式 注意這個樣式使我們自己定義的
在這里我貼出我自己定義的樣式的代碼
路徑res/values/styles
<style name="AlertDialog" parent="@android:style/Theme.DeviceDefault.Dialog"> <!--該行代碼就是設置AlertDialog的背景--> <item name="android:background">@drawable/dialog_bg</item> </style>