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

问题描述 投票:-1回答:2

我想通过将TextView放入MutableMap中来通过“ for in”注册事件。但是它说“项目”不是“文本视图”。是什么原因?

菜单['开胃菜']。 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()
      }
    }
 }
android kotlin android-event
2个回答
0
投票

仅获取地图输入值

menus.forEach {

    it.value.setOnClickListener(this)
}

希望这会有所帮助。


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}")
      }
  }
© www.soinside.com 2019 - 2024. All rights reserved.