How to set the text color of TextView in code?

后端 未结 30 2995
你的背包
你的背包 2020-11-22 07:48

In XML, we can set a text color by the textColor attribute, like android:textColor=\"#FF0000\". But how do I change it by coding?

I tried s

30条回答
  •  不知归路
    2020-11-22 08:28

    Kotlin Extension Solution

    Add these to make changing text color simpler

    For setting ColorInt

    myView.textColor = Color.BLACK // or Color.parseColor("#000000"), etc.
    
    var TextView.textColor: Int
    get() = currentTextColor
    set(@ColorInt color) {
        setTextColor(color)
    }
    

    For setting ColorRes

    myView.setTextColorRes(R.color.my_color)
    
    fun TextView.setTextColorRes(@ColorRes colorRes: Int) {
        val color = ContextCompat.getColor(context, colorRes)
        setTextColor(color)
    }
    

提交回复
热议问题