Resolved color instead of a resource id

一个人想着一个人 提交于 2019-12-17 23:15:02

问题


Recently I've seen appeared a lint error in my code:

Should pass resolved color instead of resource id here: getResources().getColor(R.color.maps_list_background_color)
MyClass.java /myapp/android/maps line 107 Android Lint Problem

I know how to resolve it the answer is in the error, the thing is I don't get why they have added this error in the linter.


回答1:


Methods that take a color in the form of an integer should be passed an RGB triple, not the actual color resource id. You must call getResources.getColor(resource).

The function you are calling is expecting an integer that is an RGB triple, not just the id of a color resource. The color resource id is still an integer, but would not produce the color that you are expecting if it was used as the RGB triple. In order to pass it the correct RGB triple for your color, you must resolve it with the getResources().getColor(R.color.example_color) call.




回答2:


Since I'm still finding this on Google and it is deprecated, I thought I'd might as well share the current method of doing this.

check getResources().getColor() is deprecated

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



回答3:


Use annotation @ColorInt to confirm that this is color not a color reference id.

See: android.support.annotation.ColorInt




回答4:


Since getResources().getColor() is deprecated, you need to do this to get the color:

int color = ContextCompat.getColor(getContext(),your_color_id);

Now you have the color with respect to the current context Set the color using:

your_view.setBackgroundColor(color);



回答5:


As for me, it's very stupid warning.

I have own class with function:

public static final void setBackgroundColor(View v, int id) {
// Here I get color by id from resources and setBackgroundColor of this color.
}

Anyway, if I try call setBackgroundColor, I get warning. But why?

So, I did simple: rename setBackgroundColor to setBackgroundColorr.

This warning activate if found name color at function name.

And yes, I do not like name setColorBackground or any other :-)




回答6:


Apparently this is caused by lint; third bullet down.

New Lint Rules

You could probably surpress this, or try implementing their syntax.



来源:https://stackoverflow.com/questions/13989319/resolved-color-instead-of-a-resource-id

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!