首页 > 解决方案 > 带有皮肤的 BottomSheetDialogFragment 主题

问题描述

如何将BottomSheetDialogFragment主题与其他主题结合?

我的应用程序具有使用主题制作的皮肤。BottomSheetDialogFragment应该有圆角,我使用以下方法实现:

 override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setStyle(BottomSheetDialogFragment.STYLE_NORMAL, R.style.CustomBottomSheetDialogTheme) /* hack to make background transparent */
 }

然后在styles.xml

<style name="CustomBottomSheetStyle" parent="Widget.Design.BottomSheet.Modal">
    <item name="android:background">@android:color/transparent</item>
</style>

<style name="CustomBottomSheetDialogTheme" parent="Theme.MaterialComponents.Light.BottomSheetDialog">
    <item name="bottomSheetStyle">@style/CustomBottomSheetStyle</item>
</style>

但是,如果我从皮肤主题中扩展,Theme.MaterialComponents.Light.BottomSheetDialog我不会得到我在皮肤主题中定义的配色方案。

那么问题来了:如何在皮肤主题中定义Dialog主题?

标签: androidandroid-themebottom-sheetmaterial-componentsmaterial-components-android

解决方案


您可以在应用程序主题中添加bottomSheetDialogTheme属性以在应用程序中全局设置 bottomsheetDialog 样式。

<style name="AppTheme" parent="Theme.MaterialComponents.*">
   ......
   <item name="bottomSheetDialogTheme">@style/BottomSheetDialog_Rounded</item>
</style>

<style name="BottomSheetDialog_Rounded" parent="@style/ThemeOverlay.MaterialComponents.BottomSheetDialog">
    <item name="bottomSheetStyle">@style/BottomSheet_Rounded</item>
</style>

否则,在您的 BottomSheetDialogFragment 中,您可以覆盖该getTheme()方法。

public class RoundedBottomSheetDialog extends BottomSheetDialogFragment {

  //....

  @Override public int getTheme() {
    return R.style.BottomSheetDialog_Rounded;
  }
}

另外要获得圆角,您可以使用以下内容:

  <!-- BottomSheet Dialog-->
  <style name="BottomSheetDialog_Rounded" parent="@style/ThemeOverlay.MaterialComponents.BottomSheetDialog">
    <item name="bottomSheetStyle">@style/BottomSheet_Rounded</item>
  </style>

  <style name="BottomSheet_Rounded" parent="Widget.MaterialComponents.BottomSheet">
    <item name="shapeAppearanceOverlay">@style/ShapeAppearanceBottomSheetDialog_Rounded</item>
  </style>

  <style name="ShapeAppearanceBottomSheetDialog_Rounded" parent="">
    <item name="cornerFamily">rounded</item>
    <item name="cornerSizeTopRight">16dp</item>
    <item name="cornerSizeTopLeft">16dp</item>
    <item name="cornerSizeBottomRight">0dp</item>
    <item name="cornerSizeBottomLeft">0dp</item>
  </style>

推荐阅读