【发布时间】:2020-06-19 23:14:14
【问题描述】:
这是一个非常有趣的情况。 我有一些android自定义视图。它具有一些属性“状态”,用于根据此属性更改复选框的可绘制状态。如您所见,此属性被声明为不可为空,我使用默认值“State.Regular”对其进行初始化。
class SomeCustomView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : AppCompatCheckBox(context, attrs) {
sealed class State {
object Regular : State()
object Specific : State()
}
// todo: it will be nice to implement statesaving
// but it's okay for now
var state: State = State.Regular
set(value) {
field = value
refreshDrawableState()
}
override fun onCreateDrawableState(extraSpace: Int): IntArray =
super.onCreateDrawableState(extraSpace + 1).apply {
val stateAttrRes = when(state) {
State.Specific -> R.attr.some_custom_view_specific
State.Regular -> R.attr.some_custom_view_regular
}
View.mergeDrawableStates(this, intArrayOf(stateAttrRes))
}
}
但是当我们要使用这个视图时,它会因为这个异常而崩溃:
kotlin.NoWhenBranchMatchedException
我曾尝试调试 when 表达式,我注意到在“onCreateDrawableState”方法中,它没有使用默认值“State.Regular”进行初始化,而是使用“null”进行初始化,这就是为什么我们有这个“NoWhenBranchMatchedException” '。
你有什么想法为什么这个属性初始化为 null 以及如何解决这个问题?
【问题讨论】:
-
解决这个问题的小技巧:在里面添加 elvis when:
when(state ?: State.Regular) ...但这是一个拐杖,Android Studio 也会将其突出显示为未使用,但它可以在运行时运行
标签: android kotlin nullpointerexception null