首页 > 解决方案 > 应用 BottomSheetDialogFragment 背景后无法更改按钮背景

问题描述

我的 BottomSheetDialogFragment 需要圆角,因此我应用了自定义可绘制对象作为其背景。但是在应用自定义背景后,BottomSheet 上的按钮不接受自定义背景。它只显示白色背景。backgroundTint 可以正常工作并更改按钮的颜色。

主题.xml:

<style name="AppBottomSheetDialogTheme"
    parent="Theme.Design.Light.BottomSheetDialog">
    <item name="bottomSheetStyle">@style/AppModalStyle</item>
</style>

<style name="AppModalStyle"
    parent="Widget.Design.BottomSheet.Modal">
    <item name="android:background">@drawable/add_new_bg</item>
</style>

add_new_bg.xml :

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid
        android:color="@color/background"/>
    <corners
        android:topLeftRadius="40dp"
        android:topRightRadius="40dp"/>
</shape>

BottomSheetDialogFragment 代码:

@Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(STYLE_NORMAL, R.style.AppBottomSheetDialogTheme);
    }

标签: androidandroid-studioandroid-bottomsheetdialogbottomsheetdialogfragment

解决方案


尝试这个 :

  1. 如果您的主题是Theme.AppCompat.Light

例子 :

<style name="Theme.YourAppName" parent="Theme.AppCompat.Light">
    <!-- Primary brand color. -->
    <!-- Customize your theme here. -->
</style>

你的按钮是:

<Button <------ material button type
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    style="@style/buttonTheme" <---- add this
    android:text="MyButton"/>

将此添加到主题下方的主题.xml 中

    <style name="buttonTheme" parent="Theme.MaterialComponents.Light">
       <item name="theme">@style/buttonTheme</item>
       <item name="android:textColor">@color/white</item>
       <item name="android:background">@color/black</item>
   </style>
  1. 如果您的主题是:Theme.MaterialComponents

例子 :

<style name="Theme.RecyclerView" parent="Theme.MaterialComponents.Light">
    <!-- Primary brand color. -->
    <!-- Customize your theme here. -->
</style>

但你的按钮使用:

<androidx.appcompat.widget.AppCompatButton <<<<--- appcompact button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        style="@style/buttonTheme" 
        android:text="MyButton"/>

然后加 :

<style name="buttonTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="theme">@style/buttonTheme</item>
    <item name="android:textColor">@color/white</item>
    <item name="android:background">@color/black</item>
</style>

按钮类型的主题必须是相同的类型。

让我知道这是否适合您..并投票赞成:)


推荐阅读