Smooth changing drawable background color of button according to some values

185 views Asked by At

my problem is that I have a button with drawable background, it's xml code is following

<Button
android:id="@+id/prolongate"
style="@style/styleBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="32dp"
android:layout_marginEnd="32dp"
android:layout_marginStart="32dp"/>

here, according to style, background of this button is drawable file with following code

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="#ff3add79" />
    <corners android:radius="128dp" />
</shape>

now I want to change background color of this button dynamically according to values, which is token from NumberPicker, but without changing its shape. I cannot create one file to one value, hardcoding is not suitable here)). How can I solve this problem?

2

There are 2 answers

2
user4551037 On BEST ANSWER

Dynamic changing the color of Drawables is possble using ColorFilter.

Drawable buttonBackground = button.getBackground();
    buttonBackground = buttonBackground.mutate();
    buttonBackground.setColorFilter(Color.parseColor("#ff0000"), Mode.SRC_IN);
    button.setBackground(buttonBackground);

https://developer.android.com/reference/android/graphics/ColorFilter also check this for modes https://developer.android.com/reference/android/graphics/PorterDuff.Mode

0
Mahavir Jain On

You can also use gradient Drawable and provide the value runtime.

val gd = GradientDrawable()
        gd.shape = GradientDrawable.RECTANGLE
        gd.setColor(Color.RED)
        gd.cornerRadius = 15.0f
        mBinding.actMainTextview.setBackground(gd)

        mBinding.actMainTextview.setOnClickListener(object : View.OnClickListener {
            override fun onClick(v: View?) {
                gd.setColor(Color.YELLOW)
            }

        })