your programing

Android 6.0 Marshmallow (API 23)에서 getColor (int id) 지원 중단됨

lovepro 2020. 9. 30. 11:12
반응형

Android 6.0 Marshmallow (API 23)에서 getColor (int id) 지원 중단됨


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부터 반환 된 색상은 지정된 Context의 테마에 맞게 스타일이 지정됩니다.


그래서 그냥 전화하십시오 :

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

코드가 잘 작동해야 getColor하고 API <23에서 더 이상 사용되지 않는 코드는 사라질 수 없습니다.


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

드로어 블용

ContextCompat.getDrawable(getApplicationContext(),R.drawable.back_arrow)

색상

 ContextCompat.getColor(getApplicationContext(),R.color.red)

당신이 사용할 수있는:

if (Build.VERSION.SDK_INT >= 23) {
    return ctx.getColor(R.color.YOURCOLOR);
} else {
    return ctx.getRecources().getColor(R.color.YOURCOLOR);
}

Android Marshmallow에서 테스트되었습니다. 효과가있었습니다.


The shortest answer is:

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

The getColor() method is deprecated in API 23, and it was introduced in ContextCompat. Before using the getColor() method using ContextCompat, add the dependencies in the build.gradle script, which is:

dependencies{

    // Other stuff

    compile 'com.android.support:support-v4:23.0.0'
}

Then the getColor() method can be used like:

int colorcode = ContextCompat.getColor(getApplicationContext(), R.color.your_color);

Code with multi API support:

if (Build.VERSION.SDK_INT < 23) {
    view.setBackgroundColor(getResources().getColor(android.R.color.white));
} else {
    view.setBackgroundColor(getContext().getColor(android.R.color.white));
}

Use the getColor(Resources, int, Theme) method of the ResourcesCompat from the Android Support Library.

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

I think it reflect better your question than the getColor(Context, int) of the ContextCompat since you ask about Resources. Prior to API level 23, the theme will not be applied and the method calls through to getColor(int) but you'll not have the deprecated warning. The theme also may be null.


In Mono / xamarin.android I had the same issue and the following code worked perfectly:

ContextCompat.GetColor (context, Resource.Color.myColor)

In my case the context is my activity (Android.Support.V7.App.AppCompatActivity) so a my real-usage example is:

var color = new Android.Graphics.Color(ContextCompat.GetColor(this, Resource.Color.myColor))    

Use this:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    return context.getResources().getColor(id, context.getTheme());
} else {
    return context.getResources().getColor(id);
}

In Your RecyclerView in Kotlin

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

Even though getColor() is deprecated in marshmallow, the replacement method
getColor(int, Theme) is available. Which can be used as an alternative to ContextCompat.getColor(context, R.color.your_color);

refer this for more information.


This way:

fab.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(this, R.color.badge_participants_counter_color)));

I got frustrated too. My need was very straightforward. All I wanted was the ARGB color from the resources, so I wrote a simple static method.

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

If you don't necessarily need the resources, use parseColor(String):
Color.parseColor("#cc0066")


With this method mentioned above: getColor(context, R.color.your_color); It is not clear how to get the "context". It won't work by just putting context there in my case, android studio 3.2. I find this works for me. .setTextColor(Color.RED).

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

반응형