如何在Android中自定义浮动动作按钮,使其在启用和禁用FAB状态下具有不同的外观和感觉?

问题描述 投票:0回答:2

我在xml中找不到FAB的启用属性。我通过在Activity的onCreate()方法中调用setEnabled(false)来禁用FAB。这样就禁用了按钮,并且onClick方法没有执行。问题是,当禁用或启用FAB时,在外观上没有区别。我如何通过xml实现启用和禁用FAB的不同外观和感觉?我试过设置clickable=false。它仍然允许按钮点击,并且onClick方法被执行。

android styles floating-action-button
2个回答
0
投票

你可以在按钮被启用时改变图标?例如,如果你的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中,请告诉我。


0
投票

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

1) 在resdrawable处创建一个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) 在resolor处创建了一个颜色选择器custom_fab_color.xml,内容如下:在FAB的启用和禁用状态下,有不同的背景颜色。

<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) 在resvaluescolors.xml中添加了启用和禁用状态所需的颜色。

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

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

<com.google.android.material.floatingactionbutton.FloatingActionButton
        ...

        android:backgroundTint="@color/custom_fab_color"
        android:src="@drawable/custom_fab" />
© www.soinside.com 2019 - 2024. All rights reserved.