【问题标题】:Properly extend a Widget class using Kotlin使用 Kotlin 正确扩展 Widget 类
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2019-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-01
      • 2017-03-22
      • 1970-01-01
      • 2019-12-15
      相关资源
      最近更新 更多