Android는 문자열 값으로 색상을 얻습니다.


104

리소스에 색상을 정의한 경우

<resources>
    <color name="someColor">#123456</color>
</resources>

ID로 색상을 설정할 수 있습니다.

view.setTextColor(R.color.someColor);

colors.xml에서 색상 문자열 값을 가져올 수도 있습니까?

같은 것

colorStr = getColor(R.color.someColor);
// -> colorStr = "#123456"

그렇다면 누구든지 예를 들어 줄 수 있습니까?

감사합니다

답변:


151

이것이 당신의 대답입니다

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

당신은 얻을 것이다

 colorStr = "#123456"

5
먼저 감사합니다. 색상에 getString을 사용할 생각은 없었습니다. 작동하지만 colorStr = "# 123456"대신 "# ff123456"이 표시되고 이것은 좋지 않습니다. :(
Tima

7
알파 작동을 제거하기 위해 반환 된 색상 문자열의 간단한 하위 문자열입니다. getResources (). getString (R.color.my_colour) .substring (3);
scottyab

82
이것은 더 이상 작동하지 않습니다. 오류 '예상 된 리소스 유형 문자열'
Clive Jefferies

21
@CliveJefferies //noinspection ResourceType진술 바로 위에 추가 할 수 있습니다 .
lordmegamax

15
getResources().getString(0+R.color.someColor);작품
18446744073709551615

139

쉬운 카피 파스타를 위해 :

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

또는 투명도없이 원하는 경우 :

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

8
내가 사용하여이를 수정하는 데 필요한 그러나 이것은 큰 일 '#' + Integer.toHexString(getResources().getColor(R.color.someColor);후에 내가 그것을 사용 이후Color.parseColor
gattsbr

4
geColor () 필요 API를> 23
Honghe.Wu

1
더 이상 사용되지 않는 getColor ()를 사용할 수 있습니다. "getColor (...)"를 삭제하고 다시 입력하고, intellisense를 사용하여 Android deprecated getColor 호출로 메서드 호출을 완료하면 좋습니다.
Wes Winn 2017

Integer.toHexString (ContextCompat.getColor (context, R.color.black) & 0x00ffffff);
AITAALI_ABDERRAHMANE

8
16 진수 색상의 처음에 0이 있으면 작동하지 않습니다.
asish

26

위에 제공된 답변은 업데이트되지 않습니다.

이것을 시도하십시오

String colorHex = "#" + Integer.toHexString(ContextCompat.getColor(getActivity(), R.color.dark_sky_blue) & 0x00ffffff);

23

Integer.toHexString()16 진수 문자열에 선행 0이있는 경우 여기에서 모든 솔루션은 break를 사용 합니다. 같은 색상 #0affff#affff. 대신 사용 :

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

또는 알파 포함 :

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

9

원인 getResources().getColor은 api> 23이 필요합니다. 따라서 이것이 더 좋습니다. 쉽게 복사 및 붙여 넣기를 위해 :

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

또는 투명도없이 원하는 경우 :`

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


ContextCompat.getColor3 개 인수를 고려하지 않습니다
하기 Nashe

@Nashe는 3 개가 아니라 2 개의 인수입니다!
Behrouz.M

4

21 이상의 API의 경우 다음을 사용할 수 있습니다.

getString(R.color.color_name);

이것은 문자열 형식으로 색상을 반환합니다. 정수 형식의 색상으로 변환하려면 (때로는 정수만 허용됨) 다음을 수행하십시오.

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

위 표현식은 color.xml 파일에 정의 된 색상에 해당하는 정수를 반환합니다.


2

오류가 발생하면 @SuppressLint ( "ResourceType")을 추가합니다. 우는 소리처럼.

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>";
    }

1

나는 그것에 대한 표준 기능이 없다고 생각합니다. 그러나 반환 값 getColor()을 16 진수로 바꾸고 16 진수 값을 문자열로 바꿀 수 있습니다 .

16 진수 123456 = 정수 1193046;


1

이것이 내가 한 방법입니다.

String color = "#" + Integer.toHexString(ContextCompat.getColor
(getApplicationContext(), R.color.yourColor) & 0x00ffffff);

1

그것은 나를 위해 작동합니다!

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

-4

당신이 사용하지 않는 경우 ContextCompat또는 SuppressLint, 단순히 추가 string하여 아래 자원 권리를 color.

대신에

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

사용하다

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

코드는 더 반복되지만 훨씬 더 깔끔합니다. 게다가 string변경 후 업데이트하는 것을 잊는 color것은 바로 옆에 있기 때문에 거의 불가능합니다.


복제는 항상 나쁜 생각입니다
Lukasz
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.