0

I have a model for which one of the setters is expecting a Color Resource but it is not to able use said resource directly without it being resolved (by making use of ContextCompat).

Is there a way that I can annotate my method to indicate/restrict this?

public class SimpleModel {
    private String name;
    private int bgColor;
    private int bgImage;

    public String getName() {
        return name;
    }

    public void setName(final String name) {
        this.name = name;
    }

    public int getBgColor() {
        return bgColor;
    }

    public void setBgColor(@ColorInt final int bgColor) {
        this.bgColor = bgColor;
    }

    public int getBgImage() {
        return bgImage;
    }

    public void setBgImage(@DrawableRes final int bgImage) {
        this.bgImage = bgImage;
    }
}

I'm aware of @ColorRes and @ColorInt -- but they don't fully resolve my issue.

Is this something that an annotation can take care of for me? What about JavaDocs?

If not -- how can I check that the resource being passed is usable?

avluis
  • 317
  • 5
  • 18
  • "I have a model for which one of the setters is expecting a Color Resource" -- that is not the model in your question, near as I can tell. You are accepting a `@ColorInt` (which is already resolved) and a `@DrawableRes` (which is not a color resource). – CommonsWare Jul 23 '17 at 21:37
  • @CommonsWare So there is no way to restrict a user from just sending `R.color.red` instead of `ContextCompat.getColor(context, R.color.red);` I realize that I didn't structure this question as best as I could. – avluis Jul 23 '17 at 21:52
  • "So there is no way to restrict a user from just sending R.color.red instead of ContextCompat.getColor(context, R.color.red)" -- that specific comparison should be caught by `@ColorInt`. `R.color.red` is not a color integer, but a color resource ID. So, with the code in your question, I would expect `model.setBgColor(R.color.red)` to result in a Lint error, while `model.setBgColor(ContextCompat.getColor(context, R.color.red))` would not. – CommonsWare Jul 23 '17 at 22:01
  • Got it -- thank you! – avluis Jul 23 '17 at 22:07

1 Answers1

1

@ColorRes denotes a requirement that the parameter be a color resource ID.

@ColorInt, in effect, is @!ColorRes, if applying a "not" operator were possible with annotations. It denotes a requirement that the parameter be an int that is not a color resource ID.

So, your public void setBgColor(@ColorInt final int bgColor) method should result in the following:

  • model.setBgColor(R.color.red) : Lint error

  • model.setBgColor(getColor(R.color.red)) : no errors

  • model.setBgColor(ContextCompat.getColor(this, R.color.red)) : no errors

If, for some reason, you need to distinguish between the latter two scenarios... I don't think there's a way to do that.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491