11

I'm trying to set the background tint of a button programmatically, not to a color resource as done here, but instead to a hex value. At the moment, I have converted a hex value into a ColorDrawable, but do not know how to use this to set the background tint with the .setBackgroundTintList() method of my button. Note that this is being done in a Fragment and the context is stored in a global variable called mContext.

ColorDrawable colorDrawable = new ColorDrawable(Color.parseColor("#FFFFFF")); 
1
  • You can use like, bLogin.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#DC143C"))); OR Commented Feb 10, 2018 at 4:51

3 Answers 3

16

on API +21

btn.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#buttonColor"))); 

or Compat

 Drawable drawable = new ColorDrawable(Color.parseColor("color")); // Wrap the drawable so that future tinting calls work // on pre-v21 devices. Always use the returned drawable. drawable = DrawableCompat.wrap(drawable); DrawableCompat.setTint(drawable,Color.parseColor("colorTint")); //or tint list //DrawableCompat.setTintList(drawable,ColorStateList.valueOf(Color.parseColor("#ffffff"))); btn.setBackground(drawable); //apply drwable with tint to the ctn 
Sign up to request clarification or add additional context in comments.

2 Comments

The second method doesn't crash on API <21 environments but is unfortunately equivalent to all the methods that replace the background - the styling disappears, there's no pressed state, etc.
However if you replace the first four lines with Drawable drawable = DrawableCompat.wrap(control.getBackground()); it works!
4

Using Compat's static functions:

ViewCompat.setBackgroundTintList(btn, ColorStateList.valueOf(Color.parseColor("#FFFFFF"))); 

Comments

1

There is 2 way :

1) get the Color name from color.xml

.setBackgroundTintList(ColorStateList.valueOf(ResourcesCompat.getColor( getResources(), R.color.your_color, null))); 

2) using hexadecimal Color String

.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#color"))); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.