使用何时使用Kotlin检查Android SDK版本

A.D*_*.D. 2 sdk android kotlin android-studio

我想在运行时检查Android SDK版本。我这样尝试:

fun Context.getDrawableById(resId : Int) : Drawable {

    when (Build.VERSION.SDK_INT) {

        in Int.MIN_VALUE..20 -> return resources.getDrawable(resId)
        else -> return getDrawable(resId)
    }
}
Run Code Online (Sandbox Code Playgroud)

我收到一个编译器警告“调用要求API级别21(当前最小值为19)”。所以我更改了代码:

fun Context.getDrawableById(resId : Int) : Drawable {

    if (Build.VERSION.SDK_INT < 21)
        return resources.getDrawable(resId)
    else
        return getDrawable(resId)
}
Run Code Online (Sandbox Code Playgroud)

没有编译器警告。

我的问题是:when在这种情况下可以使用而无需编译器警告吗?怎么样?

Oni*_*nik 5

在这种情况下,可以在没有编译器警告的情况下使用“何时”吗?

是的,使用ContextCompat.getDrawable()代替context.getDrawable()

fun View.getDrawable(resId : Int): Drawable? =
        when (Build.VERSION.SDK_INT) {
            in Int.MIN_VALUE..20 -> resources.getDrawable(resId)
            else -> ContextCompat.getDrawable(context, resId)
        }
Run Code Online (Sandbox Code Playgroud)

请注意,ContextCompat.getDrawable()返回可选类型Drawable?