How to set the text color of TextView in code?

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

    I did this way: Create a XML file, called Colors in res/values folder.

    My Colors.xml:

        
    
        #cc0000
        #4c4cff
        #000000
        #CFDBC5
        #ffffff
        #cccc00
        #66b266
    
    

    To get this colors from the xml file, I've used this code: valor it's a TextView, and ctx it's a Context object. I'm not using it from an Activity, but a BaseAdapter to a ListView. That's why I've used this Context Object.

    valor.setTextColor(ctx.getResources().getColor(R.color.azul_credito));
    

    Hope it helps.

提交回复
热议问题