在 setClickListener 期间设置时,以编程方式设置渐变不起作用。为什么?

Set gradient programmatically not working when set during setClickListener. Why?

我以编程方式设置渐变(根据 中共享的方法)

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    setTextGradient()  // Set here, and it is working
    btn_press_me.setOnClickListener {
       // Do nothing
    }
}

private fun setTextGradient() {
    val paint: TextPaint = text_happy.paint
    val width = paint.measureText(text_happy.text.toString())

    val textShader: Shader = LinearGradient(
        0f, 0f, width, text_happy.textSize, intArrayOf(
            Color.parseColor("#F97C3C"),
            Color.parseColor("#FDB54E"),
            Color.parseColor("#64B678"),
            Color.parseColor("#478AEA"),
            Color.parseColor("#8446CC")
        ), null, TileMode.CLAMP
    )
    text_happy.paint.shader = textShader
}

这行得通。但是,如果我将 setTextGradient() 移动到 setOnCLickListner,为什么它不起作用?

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    btn_press_me.setOnClickListener {
        setTextGradient()  // Move here and it is not working.
    }
}

private fun setTextGradient() {
    val paint: TextPaint = text_happy.paint
    val width = paint.measureText(text_happy.text.toString())

    val textShader: Shader = LinearGradient(
        0f, 0f, width, text_happy.textSize, intArrayOf(
            Color.parseColor("#F97C3C"),
            Color.parseColor("#FDB54E"),
            Color.parseColor("#64B678"),
            Color.parseColor("#478AEA"),
            Color.parseColor("#8446CC")
        ), null, TileMode.CLAMP
    )
    text_happy.paint.shader = textShader
}

显然我需要在设置后使它失效

    private fun setTextGradient() {
        val paint: TextPaint = text_happy.paint
        val width = paint.measureText(text_happy.text.toString())

        val textShader: Shader = LinearGradient(
            0f, 0f, width, text_happy.textSize, intArrayOf(
                Color.parseColor("#F97C3C"),
                Color.parseColor("#FDB54E"),
                Color.parseColor("#64B678"),
                Color.parseColor("#478AEA"),
                Color.parseColor("#8446CC")
            ), null, TileMode.CLAMP
        )
        text_happy.paint.shader = textShader
        text_happy.invalidate()  // Add the invalidation here
    }