Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add button tint programmatically

People also ask

How can change button background drawable in android programmatically?

If you want to do this programmatically then you just have to do: button. setBackgroundResource(R. drawable.

What is Backgroundtint?

“what is backgroundtint in android” Code Answer Friends, Background Tint Mode in android studio is use to down the background color and you can add , multiply , opacity and something else mode use to color overlapping on any background , and its support only API Level 5.0 and upper version.


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))

In properly extending dimsuz's answer by providing a real code situation, see the following code snippet:

    Drawable buttonDrawable = button.getBackground();
    buttonDrawable = DrawableCompat.wrap(buttonDrawable);
    //the color is a direct color int and not a color resource
    DrawableCompat.setTint(buttonDrawable, Color.RED);
    button.setBackground(buttonDrawable);

This solution is for the scenario where a drawable is used as the button's background. It works on pre-Lollipop devices as well.