How to set the text color of TextView in code?

后端 未结 30 3251
你的背包
你的背包 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:33

    If you still want to specify your colors in your XML file:

    #f00
    

    Then reference it in your code with one of these two methods:

    textView.setTextColor(getResources().getColor(R.color.errorColor, getResources().newTheme()));    
    

    or

    textView.setTextColor(getResources().getColor(R.color.errorColor, null));
    

    The first is probably preferable if you're compiling against Android M, however the theme you pass in can be null, so maybe that's easier for you?

    And if you're using the Compat library you can do something like this

    textView.setTextColor(ContextCompat.getColor(context, R.color.errorColor));
    

提交回复
热议问题