Is it possible to set the color of a string directly in string.xml?

前端 未结 12 1025
轮回少年
轮回少年 2021-02-07 12:17

I mean something like:

Error!
12条回答
  •  独厮守ぢ
    2021-02-07 12:48

    Prior to 4.x, you could do this:

    Error!
    

    However, bug https://code.google.com/p/android/issues/detail?id=58192 broke this functionality because it introduced an integer parser that can't handle numbers with the highest bit set, and unfortunately you can't omit the opacity part of the color (which most people would prefer to set to ff as in this example.)

    I just yesterday learned a clever work-around. What you do is negate the hex color value in two's complement. How you do this depends on your hex calculator, but the easiest way is to subtract your color from 0x100000000. In your case, that would result in 0x100000000 - 0xff9a1d1d = 0x65e2e3. (Or you could just invert it, e.g. 0065e2e2 which would be close enough). You then negate this again with a minus sign:

    Error!
    

    and voilla! you have your desired color.

    Kudos to TWiStErRob for figuring this out in https://stackoverflow.com/a/11577658/338479

    ETA: I just discovered that this will crash your app if you do it on a 2.x system; it throws a NumberFormat exception

提交回复
热议问题