使用Kotlin

时间:2017-08-11 00:04:19

标签: android enums android-widget kotlin

以下代码基本上改变了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 -> { } 
}
再次:P.S我是Kotlin的新手:),任何想法......都欢迎:)

1 个答案:

答案 0 :(得分:2)

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