【问题标题】:Check Android SDK Version with Kotlin using when使用 when 使用 Kotlin 检查 Android SDK 版本
【发布时间】:2018-06-07 08:57:56
【问题描述】:

我想在运行时检查 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)
    }
}

我收到编译器警告“调用需要 API 级别 21(当前最低为 19)”。所以我改变了我的代码:

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

    if (Build.VERSION.SDK_INT < 21)
        return resources.getDrawable(resId)
    else
        return getDrawable(resId)
}

没有编译器警告。

我的问题是:在这种情况下是否可以在没有编译器警告的情况下使用when?怎么样?

【问题讨论】:

  • Android APIs 从 1 开始,为什么使用 range from -2147483648 :) ?看起来编译器没有正确验证范围,但在大多数情况下,您只需要检查一个明确的 API 级别,其中添加了所需的方法,因此“修复”的机会非常小。
  • @Pawel 我知道 API 从 1 开始,但它没有解决它。当然,我的第一次尝试是:“in 1..20”和“else”。我认为“Int.MIN_VALUE..20”和“else”的组合涵盖了所有可能性。

标签: android kotlin sdk


【解决方案1】:

在这种情况下是否可以在没有编译器警告的情况下使用“when”?

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

fun View.getDrawable(resId : Int): Drawable? =
        when (Build.VERSION.SDK_INT) {
            in 1..20 -> resources.getDrawable(resId)
            else -> ContextCompat.getDrawable(context, resId)
        }

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-02
    • 1970-01-01
    • 2019-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多