Android get color as string value

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

If i defined a color in resources


    #123456

it\'s possible

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

    It works for me!

    String.format("#%06x", ContextCompat.getColor(this, R.color.my_color) & 0xffffff)
    
    0 讨论(0)
  • 2021-01-30 19:54

    Add @SuppressLint("ResourceType") if an error occurs. Like bellow.

    private String formatUsernameAction(UserInfo userInfo, String action) {
            String username = userInfo.getUsername();
            @SuppressLint("ResourceType") String usernameColor = getContext().getResources().getString(R.color.background_button);
            return "<font color=\""+usernameColor+"\">" + username
                    + "</font> <font color=\"#787f83\">" + action.toLowerCase() + "</font>";
        }
    
    0 讨论(0)
  • 2021-01-30 19:57

    Just for the sake of easy copypasta:

    "#" + Integer.toHexString(ContextCompat.getColor(getActivity(), R.color.some_color));
    

    Or if you want it without the transparency:

    "#" + Integer.toHexString(ContextCompat.getColor(getActivity(), R.color.some_color) & 0x00ffffff);
    
    0 讨论(0)
  • 2021-01-30 19:58

    All of the solutions here using Integer.toHexString() break if you would have leading zeroes in your hex string. Colors like #0affff would result in #affff. Use this instead:

    String.format("#%06x", ContextCompat.getColor(this, R.color.your_color) & 0xffffff)
    

    or with alpha:

    String.format("#%08x", ContextCompat.getColor(this, R.color.your_color) & 0xffffffff)
    
    0 讨论(0)
  • 2021-01-30 20:02

    Cause getResources().getColor need api > 23. So this is better: Just for the sake of easy copy & paste:

    Integer.toHexString( ContextCompat.getColor( getContext(), R.color.someColor ) );

    Or if you want it without the transparency:`

    Integer.toHexString( ContextCompat.getColor( getContext(), R.color.someColor ) & 0x00ffffff );

    0 讨论(0)
提交回复
热议问题