6

Background

I wrote a wrapper around a default Snackbar.make method to apply custom styling to my Snackbar instances. The method signature of my custom wrapper is as follows:

public static Snackbar makeCustom(
        @NonNull View view,
        @StringRes int resId,
        @Snackbar.Duration int duration)

where the Snackbar.Duration annotation is defined in android.support.design.widget.Snackbar.java as follows:

/**
 * @hide
 */
@IntDef({LENGTH_INDEFINITE, LENGTH_SHORT, LENGTH_LONG})
@IntRange(from = 1)
@Retention(RetentionPolicy.SOURCE)
public @interface Duration {}

When I invoke makeCustom with the following arguments:

makeCustom(
        activity.findViewById(android.R.id.content),
        messageResId,
        Snackbar.LENGTH_SHORT);

I see the following error in my IDE (Android Studio):

A screenshot from Android Studio showing an error associated with the parameter Snackbar.LENGTH_SHORT, which reads: "Value must be >= 1 (was 01)"

I see no such error if I directly invoke Snackbar.make, which has the following signature:

public static Snackbar make(
        @NonNull View view,
        @StringRes int resId,
        @Duration int duration) {

A screenshot from Android Studio showing no error associated with the parameter Snackbar.LENGTH_SHORT

It would appear that when used in my own method signature, Android Studio fails to recognize that values satisfying either of the following constraints

@IntDef({LENGTH_INDEFINITE, LENGTH_SHORT, LENGTH_LONG})
@IntRange(from = 1)

should be considered valid, instead expecting that values satisfy both of the above constraints simultaneously (which is impossible, since LENGTH_INDEFINITE, LENGTH_SHORT and LENGTH_LONG have values -2, -1 and 0 respectively).

Questions

  • Am I applying the Snackbar.Duration annotation properly?
  • If so:
    • Is the flagged error an Android Studio bug?
    • Is this weird behavior perhaps why the annotation is marked as hidden in the source code?
stkent
  • 19,772
  • 14
  • 85
  • 111
  • I have not played with creating these sorts of annotations. Since this is hidden, did you clone it and are using your own copy? – CommonsWare Sep 23 '16 at 12:34
  • Actually, it dawns on me that `@hide` doesn't work in libraries. It would seem like you are using it properly, but it still might be worth an experiment to clone it and refer to your copy. – CommonsWare Sep 23 '16 at 12:45
  • Cloning seems to be a suitable workaround; very odd! Thanks for the suggestion. – stkent Sep 23 '16 at 12:55
  • 1
    I agree that it's odd. After all, all the annotations come from a library. Maybe the nested interface has something to do with it. That's the first time I recall seeing a validation annotation implemented that way. – CommonsWare Sep 23 '16 at 13:05
  • 1
    This bug has been reported here: https://code.google.com/p/android/issues/detail?id=216372 – Weizhi Oct 27 '16 at 08:50
  • @Weizhi awesome find, thanks! – stkent Oct 27 '16 at 11:32

0 Answers0