이 Resources.getColor(int id)메소드는 더 이상 사용되지 않습니다.
@ColorInt
@Deprecated
public int getColor(@ColorRes int id) throws NotFoundException {
return getColor(id, null);
}
어떻게해야합니까?
이 Resources.getColor(int id)메소드는 더 이상 사용되지 않습니다.
@ColorInt
@Deprecated
public int getColor(@ColorRes int id) throws NotFoundException {
return getColor(id, null);
}
어떻게해야합니까?
답변:
Android 지원 라이브러리 23부터
새로운 getColor () 메소드가 추가되었습니다 ContextCompat.
공식 JavaDoc의 설명 :
특정 자원 ID와 연관된 색상을 리턴합니다.
M부터 시작하여 반환 된 색상은 지정된 컨텍스트 테마에 맞게 스타일이 지정됩니다.
그래서 전화하십시오 :
ContextCompat.getColor(context, R.color.your_color);
tl; dr :
ContextCompat.getColor(context, R.color.my_color)
설명:
Support V4 Library의 일부인 ContextCompat.getColor () 를 사용해야 합니다 (이전의 모든 API에서 작동 함).
ContextCompat.getColor(context, R.color.my_color)
지원 라이브러리를 아직 사용하지 않는 경우 dependencies앱 내부 의 배열에 다음 행을 추가 해야합니다 build.gradle(참고 : 이미 appcompat (V7) 라이브러리를 사용하는 경우 선택 사항 임 ).
compile 'com.android.support:support-v4:23.0.0' # or any version above
테마에 관심이있는 경우 설명서에서 다음을 지정합니다.
M부터 시작하여 반환 된 색상은 지정된 컨텍스트 테마에 맞게 스타일이 지정됩니다.
M, 반환 된 색상은 지정된 컨텍스트 테마에 따라 스타일이 지정됩니다. "라고 표시되어 있습니다.
ContextCompat클래스는 SupportV4에서 제공됩니다. AppcompatV7은 SupportV4를 사용하므로 작동합니다. 그들은에서 말하는 것처럼 지원 라이브러리 문서 , This library depends on the v4 Support Library. If you are using Ant or Eclipse, make sure you include the v4 Support Library as part of this library's classpath.. 따라서 AppcompatV7답 을 넣지 않는 것이 좋습니다 .
getColor 만 지원 라이브러리를 포함하고 싶지 않으므로 다음과 같은 것을 사용하고 있습니다
public static int getColorWrapper(Context context, int id) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return context.getColor(id);
} else {
//noinspection deprecation
return context.getResources().getColor(id);
}
}
코드가 제대로 작동하고 더 이상 사용되지 않는 getColorAPI <23에서 사라질 수 없다고 생각합니다 .
그리고 이것이 제가 Kotlin에서 사용하고있는 것입니다 :
/**
* Returns a color associated with a particular resource ID.
*
* Wrapper around the deprecated [Resources.getColor][android.content.res.Resources.getColor].
*/
@Suppress("DEPRECATION")
@ColorInt
fun getColorHelper(context: Context, @ColorRes id: Int) =
if (Build.VERSION.SDK_INT >= 23) context.getColor(id) else context.resources.getColor(id);
Android Marshmallow에서는 많은 메소드가 더 이상 사용되지 않습니다.
예를 들어 색상을 사용하려면
ContextCompat.getColor(context, R.color.color_name);
또한 드로어 블 사용하기
ContextCompat.getDrawable(context, R.drawable.drawble_name);
모든 Kotlin 사용자의 경우 :
context?.let {
val color = ContextCompat.getColor(it, R.color.colorPrimary)
// ...
}
val color = ContextCompat.getColor(context, R.color.colorPrimary). "it"변수는 무엇이든 될 수 있지만 Context 이어야합니다 .
it이 경우에는 null이 아닌지 확인하는 데 context사용 context?.let {하기 때문에 context입니다. 이 함수 getColor()는 널이 아닌 컨텍스트 만 허용합니다. 에 대한 자세한 내용은 여기를 읽어 let그것을 사용하는 방법 : kotlinlang.org/docs/reference/scope-functions.html#let
Kotlin의 RecyclerView에서
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bind(t: YourObject, listener: OnItemClickListener.YourObjectListener) = with(itemView) {
textViewcolor.setTextColor(ContextCompat.getColor(itemView.context, R.color.colorPrimary))
textViewcolor.text = t.name
}
}
Android 지원 라이브러리에서 getColor(Resources, int, Theme)방법을 사용하십시오 ResourcesCompat.
int white = new ResourcesCompat().getColor(getResources(), R.color.white, null);
나는 그것이 당신이 질문 getColor(Context, int)한 ContextCompat이후 의 것보다 당신의 질문을 더 잘 반영한다고 생각합니다 Resources. API 레벨 23 이전에는 테마가 적용되지 않고 메소드가 호출 getColor(int)되지만 더 이상 사용되지 않는 경고가 표시되지 않습니다. 테마도 있습니다 null.
반드시 리소스가 필요하지 않은 경우 다음을 사용하십시오 parseColor(String).
Color.parseColor("#cc0066")
현재 분getColor() 이라면 API 레벨은 23이며 문자열 리소스를 얻는 데 사용 하는 것처럼 간단하게 사용할 수 있습니다getString() .
//example
textView.setTextColor(getColor(R.color.green));
// if `Context` is not available, use with context.getColor()
23 이하의 API 레벨을 제한 할 수 있습니다.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
textView.setTextColor(getColor(R.color.green));
} else {
textView.setTextColor(getResources().getColor(R.color.green));
}
그러나 간단하게 유지하려면 다음과 같이 받아 들일 수있는 답변으로 할 수 있습니다.
textView.setTextColor(ContextCompat.getColor(context, R.color.green))
에서 자원 .
나도 좌절했다. 나의 필요는 매우 간단했다. 내가 원했던 것은 리소스의 ARGB 색상뿐이므로 간단한 정적 메서드를 작성했습니다.
protected static int getARGBColor(Context c, int resId)
throws Resources.NotFoundException {
TypedValue color = new TypedValue();
try {
c.getResources().getValue(resId, color, true);
}
catch (Resources.NotFoundException e) {
throw(new Resources.NotFoundException(
String.format("Failed to find color for resourse id 0x%08x",
resId)));
}
if (color.type != TYPE_INT_COLOR_ARGB8) {
throw(new Resources.NotFoundException(
String.format(
"Resourse id 0x%08x is of type 0x%02d. Expected TYPE_INT_COLOR_ARGB8",
resId, color.type))
);
}
return color.data;
}