android.content.res.TypedArray 无法转换为 java.lang.AutoCloseable

Rub*_*era 16 android kotlin

我有一个如下所示的自定义视图,我可以将其简化为:

class MyCustomView : FrameLayout {
  constructor(context: Context) : super(context) {
    initView(null)
  }
  constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
    initView(attrs)
  }

  constructor(context: Context, attrs: AttributeSet?, @AttrRes defStyleAttr: Int)
    : super(context, attrs, defStyleAttr) {
    initView(attrs)
  }

  private fun initView(attrs: AttributeSet?) {
    attrs?.let {
      context.theme.obtainStyledAttributes(attrs, R.styleable.MyCustomView, 0, 0).use {
        if (it.hasValue(R.styleable.MyCustomView_my_custom_attribute)) {
          //...
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

问题是我收到异常:执行obtainStyledAttributes方法时 android.content.res.TypedArray 无法转换为 java.lang.AutoCloseable 。

我的项目各处都使用相同的方法,但这是唯一崩溃的地方。这是为什么?

Rub*_*era 31

我意识到我正在使用接口use中的方法AutoCloseable,但是方法TypedArray返回的class 只从 Android 31 开始obtainStyledAttributes实现它,并且我正在较低的 API 上进行测试。

在它工作的地方,我使用库use中的方法androidx.core:core-ktx:1.7.0,它是向后兼容的。

总而言之,我只需添加以下导入:

import androidx.core.content.res.use
Run Code Online (Sandbox Code Playgroud)

以防万一您还没有它,请将依赖项添加到您的应用程序/库的build.gradle文件中

implementation("androidx.core:core-ktx:1.7.0")
Run Code Online (Sandbox Code Playgroud)

  • 哎呀,不错的步枪。有人需要向 Google 报告此情况,以便他们可以为此引入 lint 检查。我个人没有收到关于缺乏向后兼容性的警告。 (6认同)