The latest Android APIs have some helpful methods that are not available to older Android versions. The DatePicker, for example, has a new method called setCalendarViewShown() that is not available for old APIs such as Android 2.2 (level 8) and so on.
However, I’ve set the minimum API level to 8 and the target level to 16. So I would like to use these methods if available (on level 11+ devices).
Now I’ve tried to distinguish between several API levels programatically and, if available, call the method like this:
if (android.os.Build.VERSION.SDK_INT >= 11) {
datePicker.setCalendarViewShown(false);
}
Is this approach okay? In Eclipse, there’s just some warnings, but they can be suppressed, of course. Due to checking for the SDK_INT, this code should be fine and cause no problems, shouldn’t it?
I’d use
Build.VERSION_CODES.HONEYCOMBinstead of11for readability, but otherwise yes.Eclipse will point out that
setCalendarViewShown()does not exist in API Level 8. It has no reliable means of confirming that you are only calling that method within a version guard block, so it just complains. Using theTargetApi(11)annotation will get rid of it, while still ensuring that if you add something else to the method that needs something higher than 11, you will get warned again.Yes.
BTW, in this particular case, there’s an XML attribute you could use (
android:calendarViewShown) to replace the call. As XML attributes are automatically ignored on older versions, you could then skip theBuildcheck.