How to set the color of a TextView in Android?

前端 未结 3 1742
野性不改
野性不改 2020-12-29 00:39

In the string.xml file I use the following tag

#F5DC49

If I use

 textview1.s         


        
相关标签:
3条回答
  • 2020-12-29 01:19

    context.getResources().getColor is Deprecated.

    You need to use ContextCompat.getColor(), which is part of the Support V4 Library (so it will work for all the previous API).

    ContextCompat.getColor(context, R.color.my_color);
    

    You will need to add the Support V4 library by adding the following to the dependencies array inside your app build.gradle:

    compile 'com.android.support:support-v4:23.0.1' # or any version above
    

    If you care about theming, the documentation specifies that the method will use the context's theme:

    Starting in M, the returned color will be styled for the specified Context's theme

    0 讨论(0)
  • 2020-12-29 01:20
     textView1.setTextColor(Color.parseColor("#F5DC49"));
    

    without resources

    0 讨论(0)
  • 2020-12-29 01:28

    TextView.setTextColor() takes an int representing the color (eg. 0xFFF5DC49) and not the resource ID from the xml file. In an activity, you can do something like:

       textView1.setTextColor(getResources().getColor(R.color.mycolor))
    

    outside of an activity you'll need a Context eg.

       textView1.setTextColor(context.getResources().getColor(R.color.mycolor))
    
    0 讨论(0)
提交回复
热议问题