为什么 "setOnClickListener (this)" 在 "for in" 中不起作用?

Why doesn't "setOnClickListener (this)" work in "for in"?

我想通过 "for in" 将 TextView 放入 MutableMap 来注册一个事件。 但是它说 "item" 不是 "textview"。这是什么原因?

菜单 ['appetizers']。 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()
      }
    }
 }

只获取地图入口值

menus.forEach {

    it.value.setOnClickListener(this)
}

希望这对您有所帮助。

将此(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}")
      }
  }