我正在 android devs 網站上學習 kotlin 基礎課程,我們必須創建一個應用程式,允許您擲骰子并顯示帶有擲出數字的影像。我可以為每個可能的卷號設定條件,但我覺得這很愚蠢,并且使用格式化的參考 ID 呼叫應該做得更好,但我不知道如何使用 Android Studio 在 kotlin 中實作這一點。有幫手嗎?
package com.example.diceroller
import android.os.Bundle
import android.widget.Button
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
/**
* Calls the onCreate() method to initiate the app in its MainActivity.
* setOnClickListener to look for activity in the window (button presses/taps).
*/
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val rollButton: Button = findViewById(R.id.button)
rollButton.setOnClickListener { rollDice() }
/* Toast.makeText(this,"Dice Rolled!", Toast.LENGTH_SHORT).show() | Shows alert (toast) at bottom of the screen. */
}
/*
* Initiates a 'Dice' instance with 6 sides.
* calls the roll() method to call rng between 1 and numSides.
*
*/
private fun rollDice() {
val dice = Dice(6)
val diceRoll = dice.roll()
val diceImage: ImageView = findViewById(R.id.imageView)
if (diceRoll == 1){ diceImage.setImageResource(R.drawable.dice_1) }
else if (diceRoll == 2){ diceImage.setImageResource(R.drawable.dice_2) }
//Instead of doing it the "dumb way" I want to call the id depending on diceRoll value.
}
}
class Dice(private val numSides: Int) {
fun roll(): Int {
return (1..numSides).random()
}
}
uj5u.com熱心網友回復:
如果您詢問如何添加1或其他內容"R.drawable.dice_",然后將該字串轉換為資源 ID,那么您可以按照此處接受的答案進行操作:https : //stackoverflow.com/a/2414165/13598222
我個人不建議這樣做 - 它很脆弱,因為編譯器無法將您正在執行的操作連接到特定資源。因此,如果您更改資源名稱(因此您的代碼不再匹配),它不會警告您,并且 Proguard 之類的東西最終可能會洗掉“未使用”的資源(因為它無法告訴您正在使用它們)你必須手動修復它。
可能最標準的方法是使用when子句,然后從中回傳可繪制 ID:
val drawableId = when(diceRoll) {
1 -> R.drawable.dice_1
2 -> R.drawable.dice_2
3 -> R.drawable.dice_3
4 -> R.drawable.dice_4
5 -> R.drawable.dice_5
else -> R.drawable.dice_6
}
diceImage.setImageResource(drawableId)
當然它有點重復,但它是一個標準模式,很容易理解和使用,并且您通過添加(必需的)else子句來明確處理所有情況- 您也可以6明確處理并使 elsethrow退出 - of-range 訊息,以防您的roll函式以某種方式發送無效值(它可以,因為您在這里硬編碼了六個值,但您的Dice類可以有任意數字!)
另一種方法是進行查找,例如Map:
private val diceDrawables = mapOf {
1 to R.drawable.dice_1,
2 to R.drawable.dice_2,
3 to R.drawable.dice_3,
4 to R.drawable.dice_4,
5 to R.drawable.dice_5,
6 to R.drawable.dice_6
}
然后你的影像設定代碼可以很好而且很短:
diceImage.setImageResource(diceDrawables[diceRoll] ?: throw Exception("No image for roll: $diceRoll))
這不是“愚蠢”的做事方式,它干凈整潔,避免重復(例如重復setImageResource呼叫)。巧妙處理代碼邏輯可以減少幾行代碼,但也會使事情變得更加復雜和脆弱,而且更難處理。有時這種事情是正確的選擇,但在這種情況下,我認為這可能是最好的妥協。你的電話!
uj5u.com熱心網友回復:
使用這些資源 ID 創建一個串列。
private fun rollDice() {
val diceImages = listOf(R.drawable.dice_1, R.drawable.dice_2, ...)
val diceImage: ImageView = findViewById(R.id.imageView)
discImage.setImageResource(discImages.random())
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/357545.html
