Search code examples
androidandroid-drawable

How to change color for android:drawableStart?


I have a simple button with a drawable on the left:

<Button
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:id="@+id/color_primary"
   android:onClick="onClick"
   android:text="@string/primary"
   android:drawableLeft="@drawable/solid_color"
   android:drawablePadding="3dp"
   />

For change the drawable color I use this code:

public void setColorOnButton( int id, int color){
    Button btn = findViewById( id );
    for( Drawable drawable : btn.getCompoundDrawables()) {
        if( drawable != null){
            drawable.setColorFilter(new PorterDuffColorFilter( 0xff000000|color, PorterDuff.Mode.SRC_IN));
        }
    }
}

It is works fine.

But now I want to support "right to left" languages and I use this attribute: android:drawableStart and setColorOnButton do not work: btn.getCompoundDrawables() return nulls.

What is wrong?


Solution

  • The method getCompoundDrawables cannot return null. It returns an array of Drawables. Maybe the array has null values or is empty.

    If I understand your logic correctly, you are using android:drawableStart instead of android:drawableLeft when the language is RTL. In that case, you can use getCompoundDrawablesRelative which has access to drawables defined in:

    • start
    • top
    • end
    • bottom

    So, your code will look like this:

    public void setColorOnButton( int id, int color){
        Button btn = findViewById( id );
        for( Drawable drawable : btn.getCompoundDrawablesRelative()) {
            if( drawable != null){
                drawable.setColorFilter(new PorterDuffColorFilter( 0xff000000|color, PorterDuff.Mode.SRC_IN));
            }
        }
    }