我有一个类,它在文本字段中接受用户输入并使用提供的函数将它们转换为任何类
class GenericTextFieldDelegate<T>(
private val initBlock: () -> TextView,
private val getConversion: (String?) -> T?,
private val setConversion: (T?) -> String? = { it?.toString() }
) {
private val textView: TextView by lazy { initBlock() }
operator fun getValue(thisRef: Any?, property: KProperty<*>): T? =
getConversion(textView.text?.toString())
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T?) {
textView.text = setConversion(value)
}
}
我已经这样做了,所以当我有 TextViews 时,我可以这样做
class IntegerInputView @JvmOverloads constructor(
context: Context,
attributeSet: AttributeSet? = null,
defStyleAttr: Int = 0
) : LinearLayout(context, attributeSet, defStyleAttr), DataInput<Int> {
override var value: Int? by GenericTextFieldDelegate(
{ inputET },
getConversion = { it?.toIntOrNull() },
setConversion = { it.toString() }
)
...
我有一个具有上述自定义视图的片段,当我有
override var tareWeight: Kg?
get() = tareWeightInput.value
set(value) {
tareWeightInput.value = value
}
一切正常,我真正想做的是
override var tareWeight: Kg? by tareWeightInput
将这些行添加到IntegerInputView
...
operator fun getValue(thisRef: Any?, property: KProperty<*>): Int? = value
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Int?) {
this.value = value
}
override var value: Int? by GenericTextFieldDelegate(
...
当我构建、运行和加载片段时,我得到下面的堆栈跟踪。我哪里错了?
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Integer com.gameforeverything.storekeeper.customViews.IntegerInputView.getValue(java.lang.Object, kotlin.reflect.KProperty)' on a null object reference
at com.gameforeverything.storekeeper.fragments.weighInFragment.WeighInFragment.getGrossWeight(Unknown Source:7)
at com.gameforeverything.storekeeper.fragments.weighInFragment.WeighInPresenter.getNetWeight(WeighInPresenter.kt:40)