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

标签 kotlin typed-arrays

这是我的代码,该类用于膨胀 View 。 我在这里使用类型化数组。有没有其他方法可以编写此代码 不使用类型化数组

 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 类负责包含 Android 资源的属性值。

但是,您可以使用 Android KTX Core extensions在 Kotlin 中使其更短:

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

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

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

关于kotlin - 我们应该避免在 Kotlin 中使用类型化数组吗?如果是,有没有更新的方法来替换 Kotlin 中的类型化数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61017886/

相关文章:

java - 如何在抽屉导航中创建可选标题

android - 'when' 语句在 Kotlin for Android 中跳过条件

gradle - 如何在 intelli J IDE 中为我现有的 Kotlin 项目生成 build.gradle 文件

android - 自定义 JUnit 规则允许所有测试无论如何都通过

javascript - 三个js如何手动添加三 Angular 形到BufferGeometry

javascript - 为什么我的 Canvas 噪点功能总是只显示红色?

gradle - 使用 Kotlin 实现插件时如何为 Gradle 扩展任务?

javascript - Uint8ClampedArray 的奇怪舍入行为

javascript - Float32Array 和 Int32Array 的区别

arrays - nodejs从缓冲区数据到字节数组的转换