【问题标题】:Why does the Material FAB not change colors when disabled?为什么材质 FAB 在禁用时不改变颜色?
【发布时间】:2020-06-23 19:24:46
【问题描述】:

我正在禁用 Material Floating Action 按钮,但是当禁用设置为 true 时颜色不会改变。我认为 Material 有一个 FAB 的主题,禁用时它应该变成浅灰色。我不想在每次启用/禁用时添加代码来更改背景。

我目前正在使用材料版本:1.1.0

在代码中,我只是将 fab 设置为由 fab.isEnabled = false 禁用

这里是xml

            <com.google.android.material.floatingactionbutton.FloatingActionButton
                android:id="@+id/save_reservation_fab"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/keyline_2"
                app:backgroundTint="@color/color_primary"
                android:src="@drawable/ic_save_black_72dp"
                app:tint="@color/color_on_primary"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"/>

这是禁用/启用的工厂的样子:

它应该看起来像这样:

【问题讨论】:

    标签: android kotlin floating-action-button material-components-android


    【解决方案1】:

    怀疑这是罪魁祸首:

    app:backgroundTint="@color/color_primary"
    

    这将为您的 FAB 着色,无论其状态如何。

    您可以通过将色调设置为ColorStateList 而不是原始颜色值来解决此问题。也就是说,在您的res/color/ 目录中创建一个名为fab_color.xml 的文件,并包含以下内容:

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:state_enabled="false" android:color="your gray here"/>
        <item android:color="@color/color_primary"/>
    </selector>
    

    并将您的色调改为:

    app:backgroundTint="@color/fab_color"
    

    或者,您可以调整 Activity 的主题,使 FAB 的默认颜色为您想要的颜色 (@color/color_primary),然后完全删除 app:backgroundTint attr。

    【讨论】:

      【解决方案2】:

      版本1.2.0introduced支持FloatingActionButton中的启用/禁用状态。

      现在默认样式支持禁用状态,background color 在禁用时基于colorOnSurface

      <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:color="?attr/colorSecondary" android:state_enabled="true"/>
        <item android:alpha="0.12" android:color="?attr/colorOnSurface"/>
      </selector>
      

      您可以使用带有自定义选择器的app:backgroundTint 属性或使用:

        <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:theme="@style/ThemeOverlay.Custom.FloatingActionButton"
            ../>
      

      与:

      <style name="ThemeOverlay.Custom.FloatingActionButton" parent="">
          <item name="colorOnSurface">@color/....</item>
      </style>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-02-14
        • 2020-02-17
        • 1970-01-01
        • 2019-08-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多