我们应该避免在 Kotlin 中使用类型化数组吗?如果是,是否有更新的方法来替换 Kotlin 中的类型化数组?

Should we avoid using typed arrays in Kotlin ? If yes, Is there any newer way to replace a typed array in Kotlin?

这是我的代码,其中 class 用于扩充视图。 我在这里使用 typed array。有没有其他方法我可以写这段代码 不使用 类型数组 .

 class CalculatorInputView(context: Context, attributeSet: AttributeSet) :
    RelativeLayout(context, attributeSet) {

    init {
        LayoutInflater.from(context).inflate(R.layout.view_calculator_input, 
       this, true)

        //attribute set
        attributeSet.run {
            val typedArray: TypedArray =
                context.obtainStyledAttributes(
                    attributeSet,
                    R.styleable.CalculatorInputView
                )
            val textResource: String? =
                typedArray.getString(R.styleable.CalculatorInputView_item_text)

        }
    }
}

Is there any other way I could write this code without using the typed array.

否,因为 TypedArray class 负责包含 Android 资源的属性值。

但是,你可以使用 Kotlin 中的 Android KTX Core extensions 来缩短它:

context.withStyledAttributes(attributeSet, R.styleable.CalculatorInputView) {
   val textResource = getString(R.styleable.CalculatorInputView_item_text)
}

请记住,您需要将它们包含在您的 build.gradle:

implementation "androidx.core:core-ktx:1.2.0"