2017-08-11 181 views
0

下面的代碼基本上改變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:我是新來的科特林:),任何想法..都歡迎:)

回答

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