I want to register an event via "for in" by putting TextView in MutableMap. But it says that "item" is not "textview". What is the reason?
menus ['appetizers']. setOnClickListener (this) works.
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()
}
}
}
just get the map entry value
menus.forEach {
it.value.setOnClickListener(this)
}
Hope this helps.