使用 Kotlin 正确扩展 Widget class

Properly extend a Widget class using Kotlin

下面的代码基本上是改变按钮小部件的状态:

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)
    }
}

目标是扩展按钮小部件并避免在我的所有活动中重复代码。

是的,如果我没有 enum State,通过函数进行扩展很容易,方法如下:

fun Button.configureState(state:Int) = when(state) {
     0 -> {  //do unable stuff  }
     1 -> {  // do enable stuff } 
     else -> { // do nada }
}

My question would be what's the proper way to extend with the enum state where I could access it via Extension Function for example:

fun Button.configureWith(state: this.State) = when (state) {
    this.State.unable -> { }
    this.State.enable -> { } 
}

P.S 再次:我是 Kotlin 的新手 :),任何想法.. 欢迎 :)

您的代码将 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)
    }
}