获取颜色资源作为字符串

use*_*977 8 android android-xml android-resources

我正在尝试使用Color.parseColor()颜色资源:

<color name="redish">#FF0000</color>
Run Code Online (Sandbox Code Playgroud)

我试过这个,但它给了我错误的未知颜色:

Color.parseColor(Integer.toHexString(context.getResources().getColor(R.color.redish)))
Run Code Online (Sandbox Code Playgroud)

如何将颜色资源转换为String正确的?

N J*_*N J 19

我想你错过了#

Color.parseColor("#"+Integer.toHexString(ContextCompat.getColor(context, R.color.redish)))
Run Code Online (Sandbox Code Playgroud)

  • `Integer.toHexString(ContextCompat.getColor(context,R.color.redish)`和最近的版本对我有用. (3认同)

Dar*_*ush 7

更新的答案:

String colorHex = "#" + Integer.toHexString(ContextCompat.getColor(context, R.color.colorPrimary) & 0x00ffffff);
Run Code Online (Sandbox Code Playgroud)

  • 当接受的答案不起作用时,这对我有用。谢谢! (2认同)