programing

getColor(intid)는 Android 6.0 마시멜로(API 23)에서 사용되지 않습니다.

showcode 2023. 6. 4. 10:46
반응형

getColor(intid)는 Android 6.0 마시멜로(API 23)에서 사용되지 않습니다.

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);

다음을 확인할 수 있습니다.ContextCompat.getColor() GitHub의 소스 코드.

tl;dr:

ContextCompat.getColor(context, R.color.my_color)

설명:

지원 V4 라이브러리에 포함된 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부터 반환된 색상은 지정된 컨텍스트의 테마에 맞게 스타일이 지정됩니다.

지원 라이브러리를 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에서 사라질 수 없습니다.

제가 코틀린에서 사용하는 것은 다음과 같습니다.

/**
 * 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 Mashmallow에서는 많은 방법이 사용되지 않습니다.

예를 들어, 색상 사용 방법

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)
    // ...
}

Kotlin에서는 다음을 수행할 수 있습니다.

ContextCompat.getColor(requireContext(), R.color.stage_hls_fallback_snackbar)

함수를 호출하는 위치에서 requireContext()에 액세스할 수 있는 경우.시도할 때 오류가 발생했습니다.

ContextCompat.getColor(context, R.color.stage_hls_fallback_snackbar)

사용 중인 활동에서 ContextCompat

ContextCompat.getColor(context, R.color.color_name)

어데퍼에서

private Context context;


context.getResources().getColor()

코틀린의 재활용자 뷰에서

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

당신의 현재 최소 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))

리소스에서.

ContextCompat AndroidX에서.

컨텍스트 호환 지원에서

가장 적합한 것은 다음과 같습니다.ContextCompat.getColor그리고.ResourcesCompat.getColor빠른 마이그레이션을 위해 몇 가지 확장 기능을 만들었습니다.

@ColorInt
fun Context.getColorCompat(@ColorRes colorRes: Int) = ContextCompat.getColor(this, colorRes)

@ColorInt
fun Fragment.getColorCompat(@ColorRes colorRes: Int) = activity!!.getColorCompat(colorRes)

@ColorInt
fun Resources.getColorCompat(@ColorRes colorRes: Int) = ResourcesCompat.getColor(this, colorRes, null)

리소스가 필요하지 않은 경우 다음을 사용합니다.
Color.parseColor("#cc0066")

사용getColor(Resources, int, Theme)의 방법ResourcesCompatAndroid 지원 라이브러리에서 다운로드할 수 있습니다.

int white = ResourcesCompat.getColor(getResources(), R.color.white, null);

제 생각에 그것은 당신의 질문을 더 잘 반영한다고 생각합니다.getColor(Context, int)의 시대의ContextCompat에 대해 묻기 때문에ResourcesAPI 레벨 23 이전에는 테마가 적용되지 않으며 메소드는 다음을 호출합니다.getColor(int)하지만 더 이상 사용하지 않는 경고는 없을 겁니다또한 주제는 다음과 같습니다.null.

저도 답답했어요.제가 필요로 하는 것은 아주 간단했습니다.제가 원하는 것은 리소스의 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;
}

getColor(int)이 방법은 API 레벨 23에서 더 이상 사용되지 않습니다.사용하다getColor(int, android.content.res.Resources.Theme)대신.

에 대한 나의 시도minSDK = 21:

if(Build.VERSION.SDK_INT < 23) {
                resources.getColor(R.color.rippelColor, null)
            } else {
                resources.getColor(R.color.rippelColor)
            }

developer.android.com 의 공식 참조.

언급URL : https://stackoverflow.com/questions/31590714/getcolorint-id-deprecated-on-android-6-0-marshmallow-api-23

반응형