Home > Software engineering >  How do I adjust my function to display the correct value using the code that I am using. Is it possi
How do I adjust my function to display the correct value using the code that I am using. Is it possi

Time:05-02

How should I adjust this fun? When running the app the toast doesn't display the value, but as is. Hope that makes sense. For ex: "Option: @string/about_us" would be displayed instead of that actual value override 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)
    }

CodePudding user response:

You need to use Context#getString(stringResId) to fetch the appropriate string from the ones you've defined (this also handles fetching the appropriate language version if you're using translations). You can't use the @string/item_1 syntax here, that's an XML thing - you need to use R.string.item_1

You already have a Context (you're using it when you make the toast) so here's what I'd recommend:

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"

So you map various IDs to their string resource ID, and you run getString() with the result, so you only need to write that once instead of repeating it for every line.

By passing null when nothing matches, and null-checking before the let, you can set a fallback string - either an ID matches and gets turned into a string, or you get that string after the ?: elvis operator. Either way, selectedOption gets set to something, so you can make it a val because it's being defined right then and there

  • Related