How to set layout background tint from string programmatically?

13,901

Solution 1

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.

Solution 2

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

myView.getBackground().setTint(currentView.getResources().getColor(R.color.colorAccent));

Solution 3

For Kotlin , I modified @Krestek answer :

someLayout.background.setColorFilter(Color.parseColor("#ff8800"), PorterDuff.Mode.SRC_ATOP)
Share:
13,901
Waseem
Author by

Waseem

CONCLUSION OF MY LIFE: I play EVE Online and Dota 2 mainly, and I'm really passionate about programming and been doing it since ever I was a young kid. Currently developing my app 'Fandid' and I'm learning more and more about programming at several languages everyday :>

Updated on July 21, 2022

Comments

  • Waseem
    Waseem almost 2 years

    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
    Waseem over 6 years
    Yeah I figured, so I used other method.