gpt4 book ai didi

android - 我可以在循环中使用ArrayList ,map或hashmap作为表达式或语句来减少代码重复吗?

转载 作者:行者123 更新时间:2023-12-02 13:44:10 25 4
gpt4 key购买 nike

我的菜单项将增加很多,因此我想知道我可以在表达式中使用Array,map或hashmap来减少重复。我现在有

override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle item selection
var messages: ArrayList<String>
var timestamps: ArrayList<String>
var linknames: ArrayList<String>
var parsedData: ParsedData

return when (item.itemId) {
dataIdRead[0] -> {
Thread(Runnable {
parsedData = GetMessages(dataCity[0]).getParsedData()
timestamps = parsedData.timestamps
messages = parsedData.messages
linknames = parsedData.linknames
runOnUiThread {
rv_message_list.adapter =
MessageAdapter(messages, timestamps, linknames, this)
button.visibility = View.VISIBLE
}
}).start()
true
}

dataIdRead[1] -> {
Thread(Runnable {
parsedData = GetMessages(dataCity[1]).getParsedData()
timestamps = parsedData.timestamps
messages = parsedData.messages
linknames = parsedData.linknames
runOnUiThread {
rv_message_list.adapter =
MessageAdapter(messages, timestamps, linknames, this)
button.visibility = View.VISIBLE
}
}).start()
true
}
dataIdRead[2] -> {
Thread(Runnable {
parsedData = GetMessages(dataCity[2]).getParsedData()
timestamps = parsedData.timestamps
messages = parsedData.messages
linknames = parsedData.linknames
runOnUiThread {
rv_message_list.adapter =
MessageAdapter(messages, timestamps, linknames, this)
button.visibility = View.VISIBLE
}
}).start()
true
}
else -> super.onOptionsItemSelected(item)


   val dataIdRead = arrayOf(R.id.helsinki, R.id.vantaa, R.id.espoo)
val dataCity = arrayOf("helsinki", "vantaa", "espoo")

看起来像这样的东西
return when (item.itemId) {
*some magic* -> {
Thread(Runnable {
parsedData = GetMessages(*some magic*).getParsedData()
timestamps = parsedData.timestamps
messages = parsedData.messages
linknames = parsedData.linknames
runOnUiThread {
rv_message_list.adapter =
MessageAdapter(messages, timestamps, linknames, this)
button.visibility = View.VISIBLE
}
}).start()
true
}
else -> super.onOptionsItemSelected(item)

我已经尝试过forEach的示例,但是在开始行 return when (item.itemId) {等待表达式,但我并没有那么做。

最佳答案

您不需要为此循环。只需获取dataIdRead的索引。如果不是-1,则将该索引粘贴到dataCity中。

val index =  dataIdRead.indexOf(item.itemId) 
return if(index == -1) {
print("item not found")
super.onOptionsItemSelected(item) }
else {
Thread(Runnable {
parsedData = GetMessages(dataCity[ index ]).getParsedData()
timestamps = parsedData.timestamps
messages = parsedData.messages
linknames = parsedData.linknames
runOnUiThread {
rv_message_list.adapter =
MessageAdapter(messages, timestamps, linknames, this)
button.visibility = View.VISIBLE
}
}).start()
true
}

关于android - 我可以在循环中使用ArrayList <String>,map或hashmap作为表达式或语句来减少代码重复吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60663798/

25 4 0