Home » Android » StateListDrawable doesn't work in a LinearLayout

StateListDrawable doesn't work in a LinearLayout

Posted by: admin November 1, 2017 Leave a comment

Questions:

I’m trying to set a StateListDrawable as background in a LinearLayout but it’s not working. Only drawableDefault (in code below) is set. My class extends LinearLayout and inflate the layout.

Layout:

<LinearLayout
    android:id="@+id/layout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="horizontal"
    android:clickable="true"
    android:focusable="true"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="24dp"
        android:layout_height="24dp"
        app:srcCompat="@android:drawable/sym_def_app_icon" />
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/default_text" />
</LinearLayout>

My code is this:

private Drawable getButtonBackground() {

    GradientDrawable drawableDefault = new GradientDrawable();
    drawableDefault.setColor(Color.BLUE);

    GradientDrawable drawablePressed = new GradientDrawable();
    drawablePressed.setColor(Color.GREEN);

    GradientDrawable drawableDisabled = new GradientDrawable();
    drawableDisabled.setColor(Color.RED);

    StateListDrawable stateListDrawable = new StateListDrawable();

    stateListDrawable.addState(new int[]{android.R.attr.state_pressed}, drawablePressed);
    stateListDrawable.addState(new int[]{android.R.attr.state_focused}, drawablePressed);
    stateListDrawable.addState(new int[]{-android.R.attr.state_enabled}, drawableDisabled);

    stateListDrawable.addState(new int[]{}, drawableDefault);

    return stateListDrawable;
}

and than…

Drawable buttonBackground = getButtonBackground();

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
    this.setBackground(buttonBackground);
} else {
    this.setBackgroundDrawable(buttonBackground);
}
Answers: