【问题标题】:Android change color of FABAndroid改变FAB的颜色
【发布时间】:2015-03-17 23:23:26
【问题描述】:

SDK 中的示例中,我有一个drawable 浮动操作按钮:

<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true">
    <ripple android:color="@color/primary_light">
        <item>
            <shape android:shape="oval">
                <solid android:color="@color/primary" />
            </shape>
        </item>
    </ripple>
</item>

<item>
    <ripple android:color="@color/primary_light">
        <item>
            <shape android:shape="oval">
                <solid android:color="@color/primary" />
            </shape>
        </item>
    </ripple>
</item>
</selector>

我正在设置我的TextView 背景:

android:background="@drawable/fab_background"

有没有办法可以访问fab_background 或编辑我的TextView 背景本身来更改我的FAB 的颜色?

【问题讨论】:

  • 为什么你不能只改变
  • 我如何动态地做到这一点?我可以在 java 代码中引用 drawable 并访问该属性吗?
  • 我认为这并不容易。你可以调用 getDrawable 然后调用 applyColorFilter
  • 您的目标 API 级别是什么?
  • @alanv 我只针对 5.0+

标签: android android-drawable


【解决方案1】:

您可以通过在布局xml中设置&lt;android.support.design.widget.FloatingActionButton&gt;的以下属性来更改FAB的颜色:

app:backgroundTint="#ff0000"

【讨论】:

    【解决方案2】:

    如果您的目标是 API 21+,则可以通过将基本可绘制对象指定为 @android:color/white 并将颜色状态列表应用为着色来利用可绘制着色和可绘制颜色状态列表。

    如果您想使用平台默认的波纹颜色,您还可以选择利用可绘制主题。我在下面的示例中使用了它。

    res/values/colors.xml:

    <resources>
      <color name="fab_checked">...</color>
      <color name="fab_normal">...</color>
      ...
    </resources>
    

    res/color/fab_tint.xml:

    <selector xmlns:android="http://schemas.android.com/apk/res/android">
      <item android:state_checked="true"
            android:color="@color/fab_checked" />
      <item android:color="@color/fab_normal" />
    </selector>
    

    res/drawable/fab.xml:

    <ripple xmlns:android="http://schemas.android.com/apk/res/android"
            android:color="?android:attr/colorControlHighlight">
        <item>
            <shape android:shape="oval"
                   android:tint="@color/fab_tint">
                <solid android:color="@color/white" />
            </shape>
        </item>
    </ripple>
    

    如果你想动态改变色调,你可以打电话给Drawable.setTint(int)Drawable.setTintList(ColorStateList)

    myFab.getDrawable().mutate().setTint(Color.RED);
    

    如果你想保留选中状态的颜色,你可以创建一个新的ColorStateList 并应用它。

    ColorStateList csl = new ColorStateList(
        new int[][] {{android.R.attr.state_checked},{}},
        new int[] {Color.GREEN, Color.RED});
    myFab.getDrawable().mutate().setTintList(csl);
    

    【讨论】:

      【解决方案3】:

      你可以简单地试试这个代码,为我工作

                  app:backgroundTint="@color/colorPrimaryDark"
      

      【讨论】:

        猜你喜欢
        • 2015-12-08
        • 1970-01-01
        • 2016-04-08
        • 2018-05-18
        • 2018-08-12
        • 1970-01-01
        • 1970-01-01
        • 2020-06-23
        • 2012-05-14
        相关资源
        最近更新 更多