Android get color as string value

前端 未结 11 1460
青春惊慌失措
青春惊慌失措 2021-01-30 19:28

If i defined a color in resources


    #123456

it\'s possible

相关标签:
11条回答
  • 2021-01-30 19:37

    For API above 21 you can use

    getString(R.color.color_name);
    

    This will return the color in a string format. To convert that to a color in integer format (sometimes only integers are accepted) then:

    Color.parseColor(getString(R.color.color_name));
    

    The above expression returns the integer equivalent of the color defined in color.xml file

    0 讨论(0)
  • 2021-01-30 19:38

    The answers provided above are not updated.

    Please try this one

    String colorHex = "#" + Integer.toHexString(ContextCompat.getColor(getActivity(), R.color.dark_sky_blue) & 0x00ffffff);
    
    0 讨论(0)
  • 2021-01-30 19:38

    I don't think there is standard functionality for that. You can however turn the return in value from getColor() to hex and turn the hex value to string.

    hex 123456 = int 1193046;

    0 讨论(0)
  • 2021-01-30 19:41

    This is how I've done it:

    String color = "#" + Integer.toHexString(ContextCompat.getColor
    (getApplicationContext(), R.color.yourColor) & 0x00ffffff);
    
    0 讨论(0)
  • 2021-01-30 19:45

    If you don't want to use ContextCompat or SuppressLint, simply add a string resource right under your color.

    Instead of

    <color name="text_color">#FFFFFF</color>
    

    Use

    <color name="text_color">#FFFFFF</color>
    <string name="text_color_string">#FFFFFF</string>
    

    Your code does get more repetitive but it's much cleaner. Besides, forgeting to updating the string after changing color is almost impossible since they are right next to each other.

    0 讨论(0)
  • 2021-01-30 19:46

    This is your answer

    colorStr=getResources().getString(R.color.someColor);
    

    you will get

     colorStr = "#123456"
    
    0 讨论(0)
提交回复
热议问题