Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check Android SDK Version with Kotlin using when

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?

like image 423
A.D. Avatar asked Jun 07 '18 08:06

A.D.


People also ask

How do I know what version of Android SDK I have?

In Android Studio, click File > Project Structure. Select SDK Location in the left pane. The path is shown under Android SDK location.

How do I check SDK version?

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.

Is Android SDK version?

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.

How do I find my current Kotlin version?

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.


1 Answers

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?.

like image 190
Onik Avatar answered Nov 14 '22 23:11

Onik