I want to check the Android SDK version at runtime. I tried it like so:
fun Context.getDrawableById(resId : Int) : Drawable {
when (Build.VERSION.SDK_INT) {
in Int.MIN_VALUE..20 -> return resources.getDrawable(resId)
else -> return getDrawable(resId)
}
}
I got a compiler warning "Call requires API Level 21 (current min is 19)". So I changed my code:
fun Context.getDrawableById(resId : Int) : Drawable {
if (Build.VERSION.SDK_INT < 21)
return resources.getDrawable(resId)
else
return getDrawable(resId)
}
No compiler warning.
My question is: is it possible to use when
in this case without compiler warning? How?
In Android Studio, click File > Project Structure. Select SDK Location in the left pane. The path is shown under Android SDK location.
You can check the version number by opening the Podfile. lock file. The file can be opened with any text editor. In the example, the Mobile SDK version is 2.2.
Android SDK Build-ToolsThe latest version of the Android SDK Build tool is 30.0. 3. While downloading or updating Android in our System, one must ensure that its latest version is download in SDK Components.
IntelliJ IDEA and Android Studio suggest updating to a new release once it is out. When you accept the suggestion, it automatically updates the Kotlin plugin to the new version. You can check the Kotlin version in Tools | Kotlin | Configure Kotlin Plugin Updates.
Is it possible to use "when" in this case without compiler warning?
Yes, by using ContextCompat.getDrawable()
instead of context.getDrawable()
:
fun View.getDrawable(resId : Int): Drawable? =
when (Build.VERSION.SDK_INT) {
in 1..20 -> resources.getDrawable(resId)
else -> ContextCompat.getDrawable(context, resId)
}
Note that ContextCompat.getDrawable()
returns the optional type Drawable?
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With