How to add button tint programmatically
In the new AppCompat library, we can tint the button this way:
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/follow"
android:id="@+id/button_follow"
android:backgroundTint="@color/blue_100"
/>
How can I set the tint of the button programmatically in my code? I'm basically trying to implement a conditional coloring of the button based on some user input.
According to the documentation the related method to android:backgroundTint
is setBackgroundTintList(ColorStateList list)
Update
Follow this link to know how create a Color State List Resource.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:color="#your_color_here" />
</selector>
then load it using
setBackgroundTintList(contextInstance.getResources().getColorStateList(R.color.your_xml_name));
where contextInstance
is an instance of a Context
using AppCompart
btnTag.setSupportButtonTintList(ContextCompat.getColorStateList(Activity.this, R.color.colorPrimary));
You could use
button.setBackgroundTintList(ColorStateList.valueOf(resources.getColor(R.id.blue_100)));
But I would recommend you to use a support library drawable tinting which just got released yesterday:
Drawable drawable = ...;
// Wrap the drawable so that future tinting calls work
// on pre-v21 devices. Always use the returned drawable.
drawable = DrawableCompat.wrap(drawable);
// We can now set a tint
DrawableCompat.setTint(drawable, Color.RED);
// ...or a tint list
DrawableCompat.setTintList(drawable, myColorStateList);
// ...and a different tint mode
DrawableCompat.setTintMode(drawable, PorterDuff.Mode.SRC_OVER);
You can find more in this blog post (see section "Drawable tinting")
Seems like views have own mechanics for tint management, so better will be put tint list:
ViewCompat.setBackgroundTintList(
editText,
ColorStateList.valueOf(errorColor));
here's how to do it in kotlin:
view.background.setTint(ContextCompat.getColor(context, textColor))