Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getCompoundDrawables returns null inside of onCreateView, but not later

Tags:

android

I want to run the code below in order to tint a button's drawable on pre-lollipop devices, however button.getCompoundDrawables() is returning null for all 4 elements of the array when called inside of the Fragment's onCreateView method.

If I inspect the same Drawable[] array at a later point in time - say upon a button click event - I can see the drawable value has been correctly assigned (3 are null, 1 is valid).

Is there some button life cycle or fragment life cycle that I can rely on the compound drawables array to have been already properly initialized?

Drawable[] drawables = button.getCompoundDrawables();
        if( drawables[2] != null){
            Drawable wrapDrawable = DrawableCompat.wrap(drawables[2]);
            DrawableCompat.setTint(wrapDrawable, color);
            button.invalidate();
        }

Here's the lib versions I'm using:

compile 'com.android.support:appcompat-v7:24.1.1'
compile 'com.android.support:support-v4:24.1.1'
compile 'com.android.support:design:24.2.0'

At request, I'm including also some xml code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout        xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
 [...]  >

<Button
    android:id="@+id/bt1"
    android:background="@android:color/transparent"
    android:textAppearance="@style/ConfigButtonTheme"
    android:text="Sincronizar Música"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:drawableEnd="@drawable/ic_chevron_right_white_24dp"
    android:textAlignment="textStart"
    android:layout_width="match_parent"
    android:layout_height="60dp" />

</LinearLayout>
like image 607
Jay Avatar asked Sep 05 '16 20:09

Jay


Video Answer


2 Answers

for android:drawableRight, you should use getCompoundDrawables(), where as for android:drawableEnd, you should use getCompoundDrawablesRelative().

getCompoundDrawablesRelative()

like image 113
Chandra Sekhar Avatar answered Oct 16 '22 09:10

Chandra Sekhar


Change android:drawableEnd to android:drawableRight. Not sure why but drawableEnd returns null in onCreate() method and drawableRight works fine.

like image 38
heloisasim Avatar answered Oct 16 '22 11:10

heloisasim