Search code examples
androidfloating-action-button

FAB Change color of icon drawable


I have defined my FAB in the layout file as:

<android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/search"
        app:rippleColor="@color/primary"
        app:elevation="1dp"
        app:borderWidth="4dp" />

Here @drawable/search is a file that I created from Android Studio's Vector Asset tool (Asset Type Material Icon). It gets created as a black color. How do I change the color of the icon used inside the FAB definition?


Solution

  • 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"/>
    

    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);