使用科特林
问题描述:
下面的代码基本上改变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控件,避免我的所有活动中的代码重复。
是很容易只是通过功能扩展,如果我没有足够的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 -> { }
}
再PS:我是新来的科特林:),任何想法..都欢迎:)
答
您的代码将State
作为仅用于更改按钮状态的参数。它不需要在Button的子类中声明。您可以使用扩展功能在其外部声明它。
enum class ButtonState { unable, enable }
fun Button.configureWith(state: ButtonState, colorInt: Int = Color.BLACK) = when (state) {
ButtonState.unable -> {
clickable = false
setBackgroundColor(Color.LTGRAY)
}
ButtonState.enable -> {
clickable = true
setBackgroundColor(colorInt)
}
}