Resolved color instead of a resource id

前端 未结 6 865
名媛妹妹
名媛妹妹 2020-12-14 06: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_l

相关标签:
6条回答
  • 2020-12-14 06:11

    Apparently this is caused by lint; third bullet down.

    New Lint Rules

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

    0 讨论(0)
  • 2020-12-14 06:14

    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)
    
    0 讨论(0)
  • 2020-12-14 06:16

    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.

    0 讨论(0)
  • 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 :-)

    0 讨论(0)
  • 2020-12-14 06:23

    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);
    
    0 讨论(0)
  • 2020-12-14 06:25

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

    See: android.support.annotation.ColorInt

    0 讨论(0)
提交回复
热议问题