Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android - ViewCompat setBackgroundTintList not working in API 21

I have a AppCompatEditText with the property backgroundTint setted to an specific color. I've created a method to change the background tint programmatically and its working in all Android versions since API 17 (4.2 Jelly Bean) to API 25 (7.1.1 Nougat), except API 21 (5.0 Lollipop).

I don't know what I'm doing wrong. Here's my code:

    public void changeViewBackgroundColor(Context context, View view, int color) {
      int theColor = ContextCompat.getColor(context, color);

      if (view instanceof TintableBackgroundView) {
        ColorStateList colorStateList = ColorStateList.valueOf(theColor);
        ViewCompat.setBackgroundTintList(view, colorStateList);
      } else {
        view.setBackgroundColor(theColor);
      }

      view.invalidate();
  }
like image 900
Txuso Avatar asked May 22 '17 16:05

Txuso


1 Answers

Unfortunately, in API 21 was introduced a change that broke setBackgroundTintList when use from ViewCompat or the view itself (later fixed in API 22).

In its place you should use setSupportBackgroundTintList which you can find as a member of AppCompat* views (like AppCompatEditText)

AppCompatEditText editText = findViewById(R.id.your_view);
editText.setSupportBackgroundTintList(colorStateList);

If you want to set it in XML, just use app:setBackgroundTintList from the support library, instead of android:setBackgroundTintList

like image 120
RodXander Avatar answered Sep 29 '22 08:09

RodXander