首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android Dialog 白邊框消除:自定義 Style 設置透明背景

     編輯:程式設計綜合問答

問題現象

Dialog dialog = new Dialog(this); 彈出時四周有白邊,即使調用 requestWindowFeature(Window.FEATURE_NO_TITLE) 也無效。

Dialog 白邊框截圖

根本原因

系統預設 Theme.Dialog 包含 windowBackground(白色邊框圖片),需覆蓋為透明。

解決方案:自定義 Style

1. res/values/styles.xml 定義


<style name="CustomDialog" parent="android:style/Theme.Dialog">
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowIsFloating">true</item>
</style>

2. 代碼中應用 Style


Dialog dialog = new Dialog(this, R.style.CustomDialog);
dialog.setContentView(R.layout.customdialog); // 自定義佈局
dialog.show();

3. 佈局文件 customdialog.xml 根佈局背景也設透明


<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@android:color/transparent"
    android:orientation="vertical">
    <!-- 內容 -->
</LinearLayout>

進階:DialogFragment 兼容寫法


public class MyDialogFragment extends DialogFragment {
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Dialog dialog = new Dialog(getActivity(), R.style.CustomDialog);
        dialog.setContentView(R.layout.customdialog);
        return dialog;
    }
}

常見坑點

  • 父 Style 必須繼承 Theme.Dialog 或 Theme.AppCompat.Dialog。
  • 佈局根 View 背景若設實色會覆蓋窗口背景,務必設 transparent 或自定義 shape。
  • API 21+ 可用 android:windowBackground 設置 @null 徹底移除背景 Drawable。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved