这是我的代码,该类用于膨胀 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/