解決安卓自定義Dialog不能水平填滿螢幕
阿新 • • 發佈:2018-12-16
問題描述:
UI設計,需要展示一個底部充滿螢幕的彈出框,但是發現下面和左右都沒有充滿。 預期: 實際:
解決方案:
- 自定義的Dialog中呼叫父類建構函式時,需要設定style
- 完整自定義dialog程式碼如下: 1.CustDialog.java
package com.cxyzy.simplebottomdialog; import android.app.Dialog; import android.content.Context; import android.support.annotation.NonNull; import android.view.Gravity; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; public class CustDialog extends Dialog { public CustDialog(@NonNull Context context) { super(context,R.style.common_dialog); setContentView(R.layout.cust_dialog_layout); changeDialogStyle(); } /** * 設定dialog居下佔滿螢幕 */ private void changeDialogStyle() { Window window = getWindow(); if (window != null) { WindowManager.LayoutParams attr = window.getAttributes(); if (attr != null) { attr.height = ViewGroup.LayoutParams.WRAP_CONTENT; attr.width = ViewGroup.LayoutParams.MATCH_PARENT; attr.gravity = Gravity.BOTTOM; window.setAttributes(attr); } } } }
2.cust_dialog_layout.xml
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#FFFFFF" android:orientation="vertical"> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="8dp" android:layout_marginLeft="8dp" android:layout_marginTop="21dp" android:layout_marginEnd="8dp" android:layout_marginRight="8dp" android:text="測試dialog" android:textColor="@android:color/black" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <TextView android:id="@+id/btn_cancel" android:layout_width="0dp" android:layout_height="40dp" android:layout_marginStart="12dp" android:layout_marginLeft="12dp" android:layout_marginTop="80dp" android:layout_marginEnd="12dp" android:layout_marginRight="12dp" android:background="#E9E9E9" android:gravity="center_vertical|center_horizontal" android:text="取消" android:textColor="#5B5B5B" android:textSize="14sp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.0" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView2" /> </android.support.constraint.ConstraintLayout>
3.styles.xml中增加:
<style name="common_dialog" parent="@android:style/Theme.Dialog">
<item name="android:windowBackground">@android:color/transparent</item>
</style>