Install buttonColorNormal programmatically for Android Button with AppCompat design effect

I am using the Google Design Support Library for Android. To set the color of a button other than the application theme, I declare Button in the layout XML file as follows:

<Button
            style="@style/Widget.AppCompat.Button.Colored"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:theme="@style/MyButton" />

And then define MyButton in styles.xml as

<style name="MyButton" parent="ThemeOverlay.AppCompat">
    <item name="colorButtonNormal">@color/my_color</item>
</style>

This gives me a button according to the design support library, with the background color as the one defined @color/my_colorin my colors.xml file.

Therefore, basically use android:themeto change the attribute colorButtonNormalto obtain the desired color.

How can I achieve the same result programmatically? Basically, if I could do something like

myButton.setTheme(R.style.MyButton) 

... then I could set colorButtonNormalto get an idea.

I can not install it as

myButton.setBackgroundColor(ContextCompat.getColor(getContext(),R.color.my_color));

or don't even like it

ColorStateList colorStateList = ContextCompat.getColorStateList(getActivity(), R.color.my_color);
ViewCompat.setBackgroundTintList(myButton, colorStateList);

.

+4
1

:

public static ColorStateList getButtonColorStateList(Context context, int accentColor) {
    // get darker variant of accentColor for button pressed state
    float[] colorHSV = new float[3];
    Color.colorToHSV(accentColor, colorHSV);
    colorHSV[2] *= 0.9f;
    int darkerAccent = Color.HSVToColor(colorHSV);

    return new ColorStateList(
            new int[][] {{android.R.attr.state_pressed}, {android.R.attr.state_enabled}, {-android.R.attr.state_enabled}},
            new int[] { darkerAccent, accentColor, getColor(context, R.color.buttonColorDisabled) });
}

accentColor - . accentColor :

<color name="buttonColorDisabled">#dddddd</color>

:

mButton.setSupportBackgroundTintList(Utils.getButtonColorStateList(this, accentColor));

mButton - AppCompatButton, accentColor - .

Lollipop touch pre-Lollipop .

0

All Articles