SetSupportBackgroundTintList not working

I created a MyButton class that extends the 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 do not work. The button displays only the allowed color. I use the latest appcompat libraries and also tried the old 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?

+4
source share
1 answer

States are agreed in the order in which they are defined. So, android.R.attr.state_enabledwill be matched before android.R.attr.state_pressed.

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

- android.R.attr.state_pressed android.R.attr.state_enabled. :

  • - > android.R.attr.state_pressed, → ContextCompat.getColor(context, R.color.primary).

  • android.R.attr.state_pressed , → android.R.attr.state_enabled , → ContextCompat.getColor(context, R.color.tint).

:

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

Source: https://habr.com/ru/post/1618264/


All Articles