我想通过将TextView放在MutableMap中来通过“ for in”注册事件。 但是它说“项目”不是“ textview”。是什么原因?
菜单[开胃菜]。 setOnClickListener(此)有效。
class MainActivity : AppCompatActivity(), View.OnClickListener {
var menus :MutableMap<String, TextView> = mutableMapOf()
// on create
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
init()
}
// init Methods
// This is where I talked about.
private fun init() {
menus["appetizers"] = menu_appetizers as TextView
menus["entrees"] = menu_entrees as TextView
menus["desserts"] = menu_desserts as TextView
menus["cocktails"] = menu_cocktails as TextView
for (item in menus!!) {
if (item is TextView) {
Log.v("Yes! TextView!", "Good!")
item.setOnClickListener(this)
} else {
// always in
Log.v("No! TextView!", "${item}")
}
}
}
// Click Methods
override fun onClick(v: View?) {
// Check Id
when (v!!.id) {
R.id.menu_bookmark -> Toast.makeText(this, "boomark", Toast.LENGTH_SHORT).show()
R.id.menu_appetizers -> Toast.makeText(this, "appetizers Click!", Toast.LENGTH_SHORT).show()
R.id.menu_entrees -> Toast.makeText(this, "entrees Click!", Toast.LENGTH_SHORT).show()
R.id.menu_desserts -> Toast.makeText(this, "desserts Click!", Toast.LENGTH_SHORT).show()
R.id.menu_cocktails -> Toast.makeText(this, "cocktails Click!", Toast.LENGTH_SHORT).show()
}
}
}
答案 0 :(得分:0)
只获取地图输入值
menus.forEach {
it.value.setOnClickListener(this)
}
希望这会有所帮助。
答案 1 :(得分:0)
将此(在menus.values中的项目)更改为(在menus.values中的项目),然后重试
for (item in menus!!.values) {
if (item is TextView) {
Log.v("Yes! TextView!", "Good!")
item.setOnClickListener(this)
} else {
// always in
Log.v("No! TextView!", "${item}")
}
}