我的菜单项将增加很多,因此我想知道我可以在表达式中使用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
}