4

I saw in a android video from google developers that they implemented two methods and defined via annotation what method should be called based on the api level.

Unfortunatelly, I can`t find the video anymore(I can't remember which video was), so I searched StackOverflow for this question and found this: Different Java methods for different API Levels

In the question he used the annotation @apilevel and I can't find that annotation.

Basically, what I want to do is this:

@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private int getDisplayWidth(Display display){
    Point size = new Point();
    display.getSize(size);
    return size.x;
}

@TargetApi(Build.VERSION_CODES.FROYO)
private int getDisplayWidth(Display display){
    return display.getWidth();
}

But ADT is giving me duplicated method error.

Community
  • 1
  • 1
jonathanrz
  • 4,206
  • 6
  • 35
  • 58

1 Answers1

6

Use:

@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private int getDisplayWidth(Display display){
    if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB_MR2) {
      Point size = new Point();
      display.getSize(size);
      return size.x;
    }

    return display.getWidth();
}
CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Thanks for your answer, with your answer in this question: http://stackoverflow.com/questions/14341042/what-is-better-suppresslint-or-targetapi I understood what @TargetApi is. – jonathanrz Sep 22 '13 at 22:47
  • I believe that the only way to achieve what I wanted is with Class overload. – jonathanrz Sep 22 '13 at 22:49
  • 2
    @jonathanrz: Yes, there is no way to have two methods with the same signature (name, parameters, return type) in the same class. `@TargetApi` does not change that. – CommonsWare Sep 22 '13 at 22:56