我應該如何調整這個樂趣?運行應用程式時,toast 不會顯示該值,而是按原樣顯示。希望這是有道理的。例如:“選項:@string/about_us”將顯示而不是實際值覆寫 fun onOptionsItemSelected(item: MenuItem): Boolean {
var selectedOption = ""
when (item.itemId) {
R.id.about_us -> selectedOption = "@string/about_us"
R.id.help -> selectedOption = "@string/help"
R.id.item_1 -> selectedOption = "@string/item_1"
R.id.item_2 -> selectedOption = "@string/item_2"
R.id.item_3 -> selectedOption = "@string/item_3"
}
val text = "Option: $selectedOption"
val toastiest = Toast.LENGTH_LONG
Toast.makeText(this, text, toastiest).show()
return super.onContextItemSelected(item)
}
uj5u.com熱心網友回復:
您需要使用Context#getString(stringResId)從您定義的字串中獲取適當的字串(如果您使用翻譯,這也可以處理獲取適當的語言版本)。你不能在@string/item_1這里使用語法,這是一個 XML 的東西 - 你需要使用R.string.item_1
你已經有一個Context(你在做吐司時正在使用它)所以這是我推薦的:
val selectedOption = when (item.itemId) {
R.id.about_us -> R.string.about_us
R.id.help -> R.string.help
R.id.item_1 -> R.string.item_1
R.id.item_2 -> R.string.item_2
R.id.item_3 -> R.string.item_3
else -> null
}?.let { getString(it) } ?: "fallback message goes here"
因此,您將各種 ID 映射到它們的字串資源 ID,并getString()使用結果運行,因此您只需要撰寫一次,而不是對每一行重復它。
通過null在沒有匹配項時傳遞,并在 之前進行空檢查let,您可以設定一個后備字串 - 一個 ID 匹配并變成一個字串,或者您在?:elvis 運算子之后獲得該字串。無論哪種方式,selectedOption都設定為某些東西,因此您可以將其設定為a val,因為它在當時和那里就被定義了
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/469417.html
