我正在學習使用 android studio 構建一個簡單的 android 應用程式,我創建了一個函式來查找某些值的 id。在撰寫這個函式時,我想使用 when 陳述句(Kotlin),但遺憾的是不得不重復它。有沒有辦法將 when 陳述句的結果同時分配給多個變數?在其他語言中,我只會回傳一個我會反匯編的串列,但我找不到在 Kotlin 中執行此操作的方法。這不是什么大問題,但我喜歡優化我的代碼。
// my Kotlin function
// setting a specific state
private fun setState(num: Int) {
Log.v(TAG, num.toString())
// get the correct image id
val imageId: Int? = when (num) {
0 -> R.drawable.lemon_restart
1 -> R.drawable.lemon_tree
2 -> R.drawable.lemon_squeeze
3 -> R.drawable.lemon_drink
else -> null
}
// get the correct text to show
val txtId: Int? = when (num) {
0 -> R.string.txt_state_0
1 -> R.string.txt_state_1
2 -> R.string.txt_state_2
3 -> R.string.txt_state_3
else -> null
}
// get the correct content description for accessibility
val contentDescriptionId: Int? = when (num) {
0 -> R.string.lemon_restart_description
1 -> R.string.lemon_tree_description
2 -> R.string.lemon_squeeze_description
3 -> R.string.lemon_drink_description
else -> null
}
// setting the new stuff
val imView: ImageView = findViewById(R.id.imageState)
val txtView: TextView = findViewById(R.id.textOrder)
txtView.text = getString(txtId!!)
imView.setImageResource(imageId!!)
imView.contentDescription = getString(contentDescriptionId!!)
}
隨意盡可能地優化它
uj5u.com熱心網友回復:
您可以從 回傳Triple或您自己的資料類when,然后對其進行解構:
val (imageId, txtId, contentDescriptionId) = when (num) {
0 -> Triple(R.drawable.lemon_restart, R.string.txt_state_0, R.string.lemon_restart_description)
...
else -> Triple(null, null, null)
}
uj5u.com熱心網友回復:
因為每個場都是常數,狀態是固定的。您可以使狀態保持不變。要稍微解耦代碼,您可以創建一個單獨的類來回傳特定狀態的值。下面是一個例子:
class StateHandle private constructor(imageId: Int?, txtId: Int?, contentDescriptionId: Int?) {
companion object {
private val imageIds = arrayOf(
R.drawable.lemon_restart,
R.drawable.lemon_tree,
R.drawable.lemon_squeeze,
R.drawable.lemon_drink
)
private val txtIds = arrayOf(
R.string.txt_state_0,
R.string.txt_state_1,
R.string.txt_state_2,
R.string.txt_state_3
)
private val contentIds = arrayOf(
R.string.lemon_restart_description,
R.string.lemon_tree_description,
R.string.lemon_squeeze_description,
R.string.lemon_drink_description
)
@JvmStatic
fun getStateFor(num: Int): StateHandle {
return StateHandle(
imageIds.getOrNull(num), txtIds.getOrNull(num),
imageIds.getOrNull(num)
)
}
}
}
它并不完美,但它更具可重用性。只需呼叫#getStateFor并使用StateHandle物件。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/398996.html
