Set FAB icon color

元气小坏坏 提交于 2019-11-30 01:12:31

You can change it programmatically using ColorFilter.

//get the drawable
Drawable myFabSrc = getResources().getDrawable(android.R.drawable.ic_input_add);
//copy it in a new one
Drawable willBeWhite = myFabSrc.getConstantState().newDrawable();
//set the color filter, you can use also Mode.SRC_ATOP
willBeWhite.mutate().setColorFilter(Color.WHITE, PorterDuff.Mode.MULTIPLY);
//set it to your fab button initialized before
myFabName.setImageDrawable(willBeWhite);

Using android:tint property you can set the color like this

<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:tint="@android:color/white"
    android:src="@android:drawable/ic_input_add"
   />

If you are using Material Components

<com.google.android.material.floatingactionbutton.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="16dp"
    android:layout_gravity="bottom|end"
    app:fabSize="normal"
    app:tint="@color/colorAccent"
    app:srcCompat="@drawable/ic_google"/>

If you want to use icon default color, change app:tint="@null"

It's easier than get the drawables, you only need to access to the color filter and set it to the color that you want.

FloatingActionButton myFab = (FloatingActionButton) findViewById(R.id.myfabid);

myFab.setColorFilter(Color.WHITE);

Use the white version of ic_add from the google design site.

android:tint looks like a clean solution but it is not supported below API level 21

Using a bitmap adds less complexity to your app than attempting to change the color of an existing icon programmatically. Less complexity means fewer things to test :)

Since FloatingActionButton extends ImageView we can use ImageViewCompat to tint the icon:

ImageViewCompat.setImageTintList(
    floatingActionButton,
    ColorStateList.valueOf(Color.WHITE)
);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!