【问题标题】:How to customise Floating Action Button to have different look and feel for enabled and disabled FAB state in Android?如何自定义浮动操作按钮以在 Android 中启用和禁用 FAB 状态具有不同的外观?
【发布时间】:2023-03-18 19:30:01
【问题描述】:

禁用或启用 FAB 时外观没有差异。如何通过 xml 为启用和禁用的 FAB 实现不同的外观?

【问题讨论】:

    标签: android styles floating-action-button


    【解决方案1】:

    您可以在启用/禁用按钮时更改图标吗?例如,如果您的 FAB 有一个“加号”图像,则在禁用时将其更改为红色“加号”,在启用时将其更改为绿色。

    为此,您需要跟踪 FAB 的状态。

    private var fabEnabled = true
    
    override fun onCreate(savedInstanceState: Bundle?) {
    ...
    
    fab.setOnClickListener { view ->
        if (fabEnabled) {
            fab.setImageResource(R.drawable.ic_green_plus)
        } else {
            fab.setImageResource(R.drawable.ic_red_plus)
        }
    }
    

    根据需要更改 fabEnabled,例如通过另一个按钮。

    请注意,此答案在 Koltin 中。请告诉我您是否愿意在 java 中使用它。

    【讨论】:

    • 我们可以通过xml实现吗?
    • 您可以使用数据绑定和 Livedata。使用 Data Binding,在 XML 中,您可以观察 MainActivity 中的 fabEnabled 等变量。如果使用 LiveData 声明此变量,则每当变量从 true 更改为 false 或 false 更改为 true 时,XML 本质上都会重新绘制,因此会更新为您想要的内容,例如不同的图标。
    • 感谢您的回复。我能够使用选择器解决问题。我已经发布了答案。
    • 没问题。很高兴您最终找到了适合您的解决方案。
    【解决方案2】:

    我能够对 FAB 有不同的外观和感觉。我采取的步骤是 -

    1) 在 /res/drawable 创建了一个可绘制的 custom_fab.xml,内容如下:

    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:drawable="@drawable/fab_disabled"
            android:state_enabled="false" />
        <item android:drawable="@drawable/fab_enabled"
            android:state_enabled="true" />
    </selector>
    

    这是为启用和禁用状态提供不同的图像。

    2) 在 /res/color 创建了一个颜色选择器 custom_fab_color.xml,内容如下:

    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:color="@color/colorFabDisabled" 
            android:state_enabled="false" />
        <item android:color="@color/colorFabEnabled" android:state_enabled="true" /> 
    </selector>
    

    这是为FAB的启用和禁用状态设置不同的背景颜色。

    3) 在 res/values/colors.xml 中为启用和禁用状态添加所需的颜色

    <resources>
        ...
        <color name="colorFabEnabled">#03DAC5</color>
        <color name="colorFabDisabled">#6DABF9</color>>
    </resources>
    

    4) 更新了定义 FAB 的 xml 文件。将 src 和 backgroundTint 指向新的可绘制对象和颜色选择器。

    <com.google.android.material.floatingactionbutton.FloatingActionButton
            ...
    
            android:backgroundTint="@color/custom_fab_color"
            android:src="@drawable/custom_fab" />
    

    【讨论】:

      猜你喜欢
      • 2023-03-15
      • 2018-08-21
      • 1970-01-01
      • 2016-07-02
      • 2015-12-07
      • 2020-05-11
      • 2020-10-15
      • 2015-01-13
      相关资源
      最近更新 更多