Reputation: 1583
I need to reuse XML layout and change button color programmatically.
In Android 5 applying app:backgroundTint
in XML changes button color but I need to do it programmatically and I do it in Recyclerview
:
holder.button.supportBackgroundTintList = ContextCompat.getColorStateList(context, backgroundColorRes)
This has no effect.
Upvotes: 1
Views: 257
Reputation: 54224
The setSupportBackgroundTintList()
method is annotated with @RestrictTo({Scope.LIBRARY_GROUP})
, which means you are not supposed to call it directly. Instead, you should use ViewCompat.setBackgroundTintList()
.
Try changing your code to this instead:
val colorStateList = ContextCompat.getColorStateList(context, backgroundColorRes)
ViewCompat.setBackgroundTintList(holder.button, colorStateList)
If you look at the source code for ViewCompat.setBackgroundTintList()
, you'll see that it does different things for API 21+ (Android 5 and higher) than earlier versions. Chances are good that the "support" background tint is only applied on earlier versions of Android, and ViewCompat
will make it so that you don't have to think about that.
Upvotes: 3