代码之家  ›  专栏  ›  技术社区  ›  Lamour

使用Kotlin正确扩展小部件类

  •  0
  • Lamour  · 技术社区  · 7 年前

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

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

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

    1 回复  |  直到 7 年前
        1
  •  2
  •   BakaWaii    7 年前

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