[英]How do I adjust my function to display the correct value using the code that I am using. Is it possible this way? Thanks
How should I adjust this fun?我应该如何调整这个乐趣? When running the app the toast doesn't display the value, but as is.
运行应用程序时,toast 不显示值,但按原样显示。 Hope that makes sense.
希望这是有道理的。 For ex: "Option: @string/about_us" would be displayed instead of that actual value override fun onOptionsItemSelected(item: MenuItem): Boolean {
例如:将显示“选项:@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)
}
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).您需要使用
Context#getString(stringResId)
从您定义的字符串中获取适当的字符串(如果您使用的是翻译,这也会处理获取适当的语言版本)。 You can't use the @string/item_1
syntax here, that's an XML thing - you need to use R.string.item_1
你不能在这里使用
@string/item_1
语法,这是一个 XML 的东西 - 你需要使用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:你已经有一个
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"
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.因此,您将 map 各种 ID 转换为其字符串资源 ID,并使用结果运行
getString()
,因此您只需编写一次,而不是每行重复一次。
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.通过在没有任何匹配项时传递
null
,并在let
之前进行空值检查,您可以设置后备字符串 - ID 匹配并转换为字符串,或者您在?:
elvis 运算符之后获取该字符串。 Either way, selectedOption
gets set to something, so you can make it a val
because it's being defined right then and there无论哪种方式,
selectedOption
都会设置为某个值,因此您可以将其设置为val
因为它是在当时和那里定义的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.