簡體   English   中英

如何使用我正在使用的代碼調整我的 function 以顯示正確的值。 這樣可能嗎? 謝謝

[英]How do I adjust my function to display the correct value using the code that I am using. Is it possible this way? Thanks

我應該如何調整這個樂趣? 運行應用程序時,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)
    }

您需要使用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"

因此,您將 map 各種 ID 轉換為其字符串資源 ID,並使用結果運行getString() ,因此您只需編寫一次,而不是每行重復一次。

通過在沒有任何匹配項時傳遞null ,並在let之前進行空值檢查,您可以設置后備字符串 - ID 匹配並轉換為字符串,或者您在?: elvis 運算符之后獲取該字符串。 無論哪種方式, selectedOption都會設置為某個值,因此您可以將其設置為val因為它是在當時和那里定義的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM