11

I tried this code:

LinearLayout someLayout=(LinearLayout)view.findViewById(R.id.someLayout);
        someLayout.setBackgroundTintList(context.getResources().getColorStateList(Color.parseColor("#ff8800")));

But I'm getting an error: android.content.res.Resources$NotFoundException I'm getting the color hex from external source so I can't embed it in colors.xml. Also I want to change the tint, not the background so setBackground is not an option.

Waseem
  • 577
  • 2
  • 4
  • 18
  • Possible duplicate of [How do I create ColorStateList programmatically?](https://stackoverflow.com/questions/15543186/how-do-i-create-colorstatelist-programmatically) – Bö macht Blau Dec 15 '17 at 18:05
  • "Possible duplicate" means "if you know how to do this then you know how to solve your problem" – Bö macht Blau Dec 15 '17 at 18:06

4 Answers4

23

I figured I can't use getColorStateList() so I searched for another way to do it. At the end I was able to set color tint using the following code:

LinearLayout someLayout=(LinearLayout)view.findViewById(R.id.someLayout);
        someLayout.getBackground().setColorFilter(Color.parseColor("#ff8800"), PorterDuff.Mode.SRC_ATOP);

This worked as if I changed the backgroundTint property in the xml file, so it's perfect for my problem.

Waseem
  • 577
  • 2
  • 4
  • 18
11

I was able to manage using the following line. change it to your circumstances.

myView.getBackground().setTint(currentView.getResources().getColor(R.color.colorAccent));
Jin Lim
  • 1,759
  • 20
  • 24
2

For Kotlin , I modified @Krestek answer :

someLayout.background.setColorFilter(Color.parseColor("#ff8800"), PorterDuff.Mode.SRC_ATOP)
Kabir
  • 852
  • 7
  • 11
-1

You can't do this like that because getColorStateList method expect int id of resource, and you are passing RGB color int. You should create color state list following this link

and then set it like this:

.getColorStateList(R.color.your_xml_name)
C. Alen
  • 184
  • 1
  • 10