Solution 1 :
Apparently, I need to invalidate it after setting it
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
}
Problem :
I programmatically set the gradient (as per the approach shared in https://stackoverflow.com/a/52289927/3286489)
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
}
This works. However, if I move setTextGradient()
into the setOnCLickListner
, why it is not working?
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
}