getColorStateList has been deprecated

There's also a newer approach:

AppCompatResources.getColorStateList(context, R.color.bar_green)

This keeps a weak reference to a cache of ColorStateList's that it has inflated and if it fails to load one, it falls back to ContextCompat.getColorStateList.


Exactly if you are using them , you will lose all styles. For an older version you should create ColorStateList dynamically, This is main chance to keep your styles.

this works for all versions

layout.setColorStateList(buildColorStateList(this,
   R.attr.colorPrimaryDark, R.attr.colorPrimary)
);


public ColorStateList buildColorStateList(Context context, @AttrRes int pressedColorAttr, @AttrRes int defaultColorAttr){
    int pressedColor = getColorByAttr(context, pressedColorAttr);
    int defaultColor = getColorByAttr(context, defaultColorAttr);

    return new ColorStateList(
            new int[][]{
                    new int[]{android.R.attr.state_pressed},
                    new int[]{} // this should be empty to make default color as we want
            }, new int[]{
            pressedColor,
            defaultColor
    }
    );
}

@ColorInt
public static int getColorByAttr(Context context, @AttrRes int attrColor){

    if (context == null || context.getTheme() == null)
        return -1;

    Resources.Theme theme = context.getTheme();
    TypedValue typedValue = new TypedValue();

    theme.resolveAttribute(attrColor, typedValue,true);

    return typedValue.data;
} 

The Theme object is the theme that is used to style the color state list. If you aren't using any special theming with individual resources, you can either pass null or the current theme as follows:

TextView valorslide; // initialize
SeekBar seekBar; // initialize
Context context = this;
Resources resources = context.getResources();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
    seekBar.setProgressTintList(resources.getColorStateList(R.color.bar_green, context.getTheme()));
    valorslide.setTextColor(resources.getColorStateList(R.color.text_green, context.getTheme()));
} else {
    seekBar.setProgressTintList(resources.getColorStateList(R.color.bar_green));
    valorslide.setTextColor(resources.getColorStateList(R.color.text_green));
}

If you don't don't care about the theme, you can just pass null:

getColorStateList(R.color.text_green, null)

See the documentation for more explanation. Note, you only need to use the new version on API 23 (Android Marshmallow) and above.


While anthonycr's answer works, it is a lot more compact to just write

ContextCompat.getColorStateList(context, R.color.haml_indigo_blue);