以编程方式从Appcompat 22.2.0更改浮动操作按钮的颜色

use*_*644 23 java android android-layout floating-action-button

我想知道如何更改支持库22.2.0中的浮动操作按钮颜色?我试过了

button.setBackgroundColor(color);
Run Code Online (Sandbox Code Playgroud)

但显然,这会改变按钮的可绘制性并变为正方形.

现在我想知道如何改变颜色而不仅仅是颜色,而不会触及形状?

提前致谢

Olu*_*ith 34

也许迟到但可以提供帮助.

 fab.setBackgroundTintList(ColorStateList.valueOf(Color
                    .parseColor("#33691E")));
Run Code Online (Sandbox Code Playgroud)

并从您可以在此处找到的颜色列表中解析实际颜色代码

  • 只是添加到此:如果您不想使用硬编码的字符串颜色值,而是引用colors.xml中存储的颜色,则可以使用以下命令:`fab.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor) (getActivity(),R.color.white)));` (4认同)

tac*_*lux 31

创建一个ColorStateList并将其设置为背景色调:

button.setBackgroundTintList(new ColorStateList(new int[][]{new int[]{0}}, new int[]{color}));
Run Code Online (Sandbox Code Playgroud)

  • 或者只是```ColorStateList.valueOf(color)```,来自:http://stackoverflow.com/a/32031019/1773325 (12认同)
  • 不起作用,需要min api 21 (4认同)

Sae*_*ish 11

你必须使用

  • 用XML格式 attribute app:backgroundTint
  • 在.setBackgroundTintList的代码中读取此答案

Android更改浮动操作按钮颜色


Ada*_*hns 10

colors.xml(R.color.purple在这种情况下)创建一个颜色资源并像这样使用它:

floatingActionButton.setBackgroundTintList(getResources().getColorStateList(R.color.purple));
Run Code Online (Sandbox Code Playgroud)

  • 请考虑与您的代码一起使用的解释性文字,以帮助未来的读者. (2认同)

Ral*_*ina 9

为此向后兼容:

DrawableCompat.setTintList(DrawableCompat.wrap(fab.getDrawable()), tintColor); // <- icon
DrawableCompat.setTintList(DrawableCompat.wrap(fab.getBackground()), backgroundTintColor); // <- background
Run Code Online (Sandbox Code Playgroud)


小智 9

方法1:更改xml中的浮动操作栏(fab)颜色:

要更改浮动操作栏(fab)颜色,请按照此步骤操作

只需在xml的浮动操作栏(fab)中添加"app:backgroundTint ="#colorcode"".例如

app:backgroundTint="#8393ca"
Run Code Online (Sandbox Code Playgroud)

在#8393ca的地方添加您想要的任何颜色代码

例如,美国..

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/fab_margin"
    app:backgroundTint="#8393ca"
    android:src="@drawable/send" />
Run Code Online (Sandbox Code Playgroud)

方法2:以编程方式更改浮动操作栏颜色

只需在代码中添加此行即可

首先在values => colors中创建一个红色,然后在create中的活动中添加此代码

fab.setBackgroundTintList(getResources().getColorStateList(R.color.red));

                                or

fab.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#33691E")));
Run Code Online (Sandbox Code Playgroud)

学分:http://androidrace.com/2016/12/12/how-to-change-fabfloating-action-bar-color-android/


Lou*_*CAD 6

在此处检查接受的答案:Android更改浮动操作按钮颜色

如果你想改变颜色

  • 在XML中使用属性app:backgroundTint
  • .setBackgroundTintList的代码中


flo*_*gny 1

属性名称是backgroundTint

所以我认为有一个名为

button.setBackgroundTint(color)