【发布时间】:2018-01-19 09:02:05
【问题描述】:
下面的代码基本上是在改变一个Button Widget的状态:
enum class State { unable, enable }
fun configureState(currentState:State, button:Button ,colorInt :Int = Color.BLACK) = when (currentState)
{
State.unable -> {
button.isClickable = false
button.setBackgroundColor(Color.LTGRAY)
button.setTextColor(Color.WHITE)
}
State.enable -> {
button.isClickable = true
button.setBackgroundColor(colorInt)
button.setTextColor(Color.WHITE)
}
}
目标是扩展 Button Widget 并避免在我的所有活动中重复代码。
是的,如果我没有enum State,通过函数扩展很容易,通过执行以下操作:
fun Button.configureState(state:Int) = when(state) {
0 -> { //do unable stuff }
1 -> { // do enable stuff }
else -> { // do nada }
}
我的问题是使用枚举状态进行扩展的正确方法是什么,例如我可以通过扩展函数访问它:
fun Button.configureWith(state: this.State) = when (state) {
this.State.unable -> { }
this.State.enable -> { }
}
再次附注:我是 Kotlin 的新手 :),任何想法 .. 都欢迎 :)
【问题讨论】:
标签: android enums android-widget kotlin