Is DrawableCompat.setTint() lazy?

0

I am designing an app that has 3 button in main activity, and several buttons in a fragment. I want to change the color of a button in the fragment, depending on which button of main activity is toggled.

color1.setOnClickListener {
        brush_chosen = 1

        color1.setBackgroundColor(R.color.black)
        color2.setBackgroundColor(0x00000000)
        color3.setBackgroundColor(0x00000000)
        if (frag_num == 8 ){
            frag_8p.set_frag_value(frag_num,brush_chosen)
        }
        
    }

The function set_frag_value is :

fun set_frag_value(frag_num:Int,brush:Int) : Int
{
    brush_chosen=brush
    return brush
}

This change the value of brush_chosen. Then I made a function :

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    ib0.setOnClickListener { view ->
        Log.d("brush_color","Brush of 0 : "+brush_chosen)
        if (brush_chosen==1)
        {
            Log.d("brush_color","Brush Confirm : "+brush_chosen)
            DrawableCompat.setTint(ib0.drawable, ContextCompat.getColor(requireContext(),R.color.rndcolor1))
        }
        else if (brush_chosen==2)
        {
            Log.d("brush_color","Brush Confirm : "+brush_chosen)
            DrawableCompat.setTint(ib0.drawable, ContextCompat.getColor(requireContext(),R.color.purple_500))
        }
        else if (brush_chosen==3)
        {
            Log.d("brush_color","Brush Confirm : "+brush_chosen)
            DrawableCompat.setTint(ib0.drawable, ContextCompat.getColor(requireContext(),R.color.teal_200))
        }
        Log.d("brush_color","End of onclicklistener ")

    }
}

I checked the log and theoretically this code should work correctly. However, I found that the button color did not change properly, even I checked my app prints all log correctly. For example, when I clicked button color1 in main activity, variable brush_chosen becomes 1 and the first button in fragment I clicked changes its color. But the second button I clicked does not change its color.

Is there any problem on my code using DrawableCompat ??

android
kotlin
android-drawable
asked on Stack Overflow Nov 13, 2020 by MooNChilD Song

1 Answer

1

Android does some Drawable state caching under the hood. You might need to call mutate() on the Drawable you want to tint and then set the new Drawable in order for the tint to show up properly.

answered on Stack Overflow Nov 14, 2020 by tylerbwong

User contributions licensed under CC BY-SA 3.0