Robin Dijkhof
Robin Dijkhof

Reputation: 19288

setSupportBackgroundTintList states not working

I created a MyButton class which extends AppCompat button. In my onstructors I execute this code:

    int[][] states = new int[][]{
            new int[]{android.R.attr.state_enabled}, // enabled
            new int[]{android.R.attr.state_pressed}  // pressed
    };

    int[] colors = new int[]{
            ContextCompat.getColor(context, R.color.tint),
            ContextCompat.getColor(context, R.color.primary),
    };

    setSupportBackgroundTintList(new ColorStateList(states, colors));

Unfortunately the states are not working. The button only shows the enabled color. I'm using the newest appcompat libs and also tried older ones

compile 'com.android.support:appcompat-v7:23.1.1'  //also tried 23.0.1
compile 'com.android.support:design:23.1.1'        //also tried 23.0.1

What am I doing wrong?

Upvotes: 4

Views: 1032

Answers (1)

Vikram
Vikram

Reputation: 51581

States are matched in the order that they are defined. So, android.R.attr.state_enabled will be matched before android.R.attr.state_pressed.

Since the button is enabled, the first positive match will be against android.R.attr.state_enabled and color ContextCompat.getColor(context, R.color.tint) will be chosen. Since, a positive match has been found, it does not matter if the button is pressed or not.

The quickest way to sort this out is to place android.R.attr.state_pressed before android.R.attr.state_enabled. State matching will go as follows:

  • button is currently pressed --> state android.R.attr.state_pressed will be checked against and a positive match will be found --> color ContextCompat.getColor(context, R.color.primary) will be used.

  • button is currently not pressed --> state android.R.attr.state_pressed will be checked against and the check will fail --> state android.R.attr.state_enabled will be checked against and a positive match will be found --> color ContextCompat.getColor(context, R.color.tint) will be used.

This should work:

int[][] states = new int[][]{
        new int[]{android.R.attr.state_pressed}, // pressed
        new int[]{android.R.attr.state_enabled} // enabled
};

int[] colors = new int[]{
        ContextCompat.getColor(context, R.color.primary),
        ContextCompat.getColor(context, R.color.tint)
};

setSupportBackgroundTintList(new ColorStateList(states, colors));

Upvotes: 4

Related Questions