Programing

컬러 리소스에서 color-int 가져 오기

lottogame 2020. 2. 21. 22:04
반응형

컬러 리소스에서 color-int 가져 오기


컬러 리소스에서 color-int를 얻는 방법이 있습니까? 리소스 (R.color.myColor)에 정의 된 색상의 개별 빨강, 파랑 및 녹색 구성 요소를 가져 와서 세 개의 탐색 막대의 값을 특정 수준으로 설정할 수 있습니다.


검색 결과에이 질문을 표시하는 데 도움이되는 다른 사용 사례에 대한 자세한 내용을 보려면 리소스에 정의 된 색상에 알파를 적용하고 싶었습니다.

@sat의 정답 사용 :

int alpha = ... // 0-255, calculated based on some business logic
int actionBarBackground = getResources().getColor(R.color.actionBarBackground);
int actionBarBackgroundWithAlpha = Color.argb(
        alpha,
        Color.red(actionbarBackground),
        Color.green(actionbarBackground),
        Color.blue(actionbarBackground)
);

당신이 사용할 수있는:

getResources().getColor(R.color.idname);

사용자 정의 색상을 정의하는 방법은 여기를 확인하십시오.

http://sree.cc/google/android/defining-custom-colors-using-xml-in-android

EDIT (1) : 이후 getColor(int id)되고 사용되지 않는 지금,이 사용해야합니다 :

ContextCompat.getColor(context, R.color.your_color);

(지원 라이브러리 23에 추가됨)

편집 (2) :

아래 코드는 마시멜로 사전 및 사후에 모두 사용할 수 있습니다 (API 23).

ResourcesCompat.getColor(getResources(), R.color.your_color, null); //without theme

ResourcesCompat.getColor(getResources(), R.color.your_color, your_theme); //with theme

새로운 Android 지원 라이브러리 (및 업데이트)를 기반으로 다음을 호출해야합니다.

ContextCompat.getColor(context, R.color.name.color);

설명서 에 따르면 :

public int getColor (int id)

이 메소드는 API 레벨 23 에서 더 이상 사용되지 않습니다 . 대신 getColor (int, Theme)를 사용하십시오.

동일한 솔루션입니다 getResources().getColorStateList(id).

다음과 같이 변경해야합니다.

ContextCompat.getColorStateList(getContext(),id);

2019 수정

ThemeOverlay가장 가까운보기의 컨텍스트 사용 과 관련 하여 :

val color = ContextCompat.getColor(
  closestView.context,
  R.color.name.color
)

따라서이 방법으로 ThemeOverlay를 기반으로 올바른 색상을 얻을 수 있습니다.

동일한 활동에서 어두운 / 빛 테마와 같은 다른 테마를 사용할 때 특히 필요합니다. 테마 및 스타일에 대한 자세한 내용을 보려면이 대화를 제안하십시오. 스타일을 사용하여 테마 개발

Nick Butcher-Droidcon Berlin-스타일을 사용한 테마 개발


색을 정의하십시오

values ​​/ color.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <!-- color int as #AARRGGBB (alpha, red, green, blue) -->
    <color name="orange">#fff3632b</color>
    ...
    <color name="my_view_color">@color/orange</color>

</resources>

색상을 가져 와서 설정하십시오.

int backgroundColor = ContextCompat.getColor(context, R.color.my_view_color);
// Color backgroundColor = ... (Don't do this. The color is just an int.)

myView.setBackgroundColor(backgroundColor);

또한보십시오


ContextCompat.getColor(context, R.color.your_color);NullPointerExcepiton을 유발하는 사용하도록 업데이트 되었지만 때로는 (일부 장치 / Android 버전에서는 확실하지 않습니다.)

따라서 모든 장치 / 버전에서 작동하도록하기 위해 null 포인터의 경우 이전 방식으로 되돌아갑니다.

try {
    textView.setTextColor(ContextCompat.getColor(getActivity(), R.color.text_grey_dark));
}
catch(NullPointerException e) {
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        textView.setTextColor(getContext().getColor(R.color.text_grey_dark));
    }
    else {
        textView.setTextColor(getResources().getColor(R.color.text_grey_dark));
    }
}

최고의 접근법

@ 토요일 대답으로 색상을 얻는 좋은 접근 방식은

ResourcesCompat.getColor(getResources(), R.color.your_color, null);

getResources()방법에 액세스 할 수없는 경우 아래 방법으로 사용하십시오 .

Context context  = getContext(); // like Dialog class
ResourcesCompat.getColor(context.getResources(), R.color.your_color, null);

내가하는 일은

public void someMethod(){
    ...
    ResourcesCompat.getColor(App.getRes(), R.color.your_color, null);
}

앱 어디에서나 사용하는 것이 가장 간단합니다! Util 클래스 또는 Context 또는 getResource ()가없는 클래스에서도

문제 (컨텍스트가 없을 때)

당신이없는 Context액세스를 당신의 방법처럼 Util클래스입니다.

컨텍스트가없는 아래 메소드를 가정하십시오.

public void someMethod(){
    ...
    // can't use getResource() without Context.
}

이제이 Context방법에서 매개 변수로 전달 하고getResources().

public void someMethod(Context context){
    ...
    context.getResources...
}

여기에 어디에서나 리소스에 액세스 할 수 있는 보너스 고유 솔루션 이 있습니다 Util class. 추가 Resources귀하의에 Application클래스 또는 존재하지 않는 경우 하나를 만듭니다.

import android.app.Application;
import android.content.res.Resources;

public class App extends Application {
    private static App mInstance;
    private static Resources res;


    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
        res = getResources();
    }

    public static App getInstance() {
        return mInstance;
    }

    public static Resources getResourses() {
        return res;
    }

}

manifest.xml <application태그에 이름 필드를 추가하십시오 . (아직 추가하지 않은 경우)

<application
        android:name=".App"
        ...
        >
        ...
    </application>

이제 잘 가세요. ResourcesCompat.getColor(App.getRes(), R.color.your_color, null);앱 어디에서나 사용하십시오 .


여기에 대한 답변은 너무 복잡합니다. 지원 라이브러리가 필요하지 않습니다.

API 23 이전 (마시멜로)

getResources().getColor(R.color.idname);

getResources().getColor(R.color.idname, null);

수표를 추가하면 완료됩니다.

int color = Build.VERSION.SDK_INT<23 ? getResources().getColor(R.color.idname) : getResources().getColor(R.color.idname,null)

비 활동 클래스에서 색상에 액세스하는 것은 어려울 수 있습니다. 내가 찾은 대안 중 하나는을 사용하는 것 enum입니다. enum많은 유연성을 제공합니다.

public enum Colors
{
  COLOR0(0x26, 0x32, 0x38),    // R, G, B
  COLOR1(0xD8, 0x1B, 0x60),
  COLOR2(0xFF, 0xFF, 0x72),
  COLOR3(0x64, 0xDD, 0x17);


  private final int R;
  private final int G;
  private final int B;

  Colors(final int R, final int G, final int B)
  {
    this.R = R;
    this.G = G;
    this.B = B;
  }

  public int getColor()
  {
    return (R & 0xff) << 16 | (G & 0xff) << 8 | (B & 0xff);
  }

  public int getR()
  {
    return R;
  }

  public int getG()
  {
    return G;
  }

  public int getB()
  {
    return B;
  }
}

ContextCompat.getColor (context, R.color.your_color);

활동 중

ContextCompat.getColor (actvityname.this, R.color.your_color);

조각으로

ContextCompat.getColor (getActivity (), R.color.your_color);

예를 들어 :

tvsun.settextcolour (ContextCompat.getColor (getActivity (), R.color.your_color))


그냥 어때?

final int Activity.getColor(int resourceID)

더 이상 사용되지 않는 곳을 알 수 없습니다.

참고 URL : https://stackoverflow.com/questions/5271387/get-color-int-from-color-resource



반응형