我为此做一些按钮和听众。但我认为这太长了,太复杂了。
所以我可以更简单地得到它吗?

这是我的代码

fun init_cardView() {
    activity_cardview.setOnClickListener(myOnClickListener)
    alertdialog_cardview.setOnClickListener(myOnClickListener)
    animation_cardview.setOnClickListener(myOnClickListener)
    widgets_cardview.setOnClickListener(myOnClickListener)
    container_cardview.setOnClickListener(myOnClickListener)
    date_cardview.setOnClickListener(myOnClickListener)
    explicitintent_cardview.setOnClickListener(myOnClickListener)
    implicitintent_cardview.setOnClickListener(myOnClickListener)
    fragment_cardview.setOnClickListener(myOnClickListener)
    wifimanager_cardview.setOnClickListener(myOnClickListener)
    menu_cardview.setOnClickListener(myOnClickListener)
    image_cardview.setOnClickListener(myOnClickListener)
    time_cardview.setOnClickListener(myOnClickListener)
    toast_cardview.setOnClickListener(myOnClickListener)
}

fun init_MyOnClickListener() {
    myOnClickListener = View.OnClickListener {
        var intent: Intent? = null
        when (it.id) {
            R.id.activity_cardview -> intent = Intent(applicationContext, Activity::class.java)
            R.id.alertdialog_cardview -> intent =
                Intent(applicationContext, AlertDialog::class.java)
            R.id.animation_cardview -> intent =
                Intent(applicationContext, Animation::class.java)
            R.id.widgets_cardview -> intent = Intent(applicationContext, Widgets::class.java)
            R.id.container_cardview -> intent =
                Intent(applicationContext, Container::class.java)
            R.id.date_cardview -> intent = Intent(applicationContext, Date::class.java)
            R.id.explicitintent_cardview -> intent =
                Intent(applicationContext, ExplicitIntent::class.java)
            R.id.implicitintent_cardview -> intent =
                Intent(applicationContext, ImplicitIntent::class.java)
            R.id.fragment_cardview -> intent = Intent(applicationContext, Fragment::class.java)
            R.id.wifimanager_cardview -> intent =
                Intent(applicationContext, WifiManager::class.java)
            R.id.menu_cardview -> intent = Intent(applicationContext, Menu::class.java)
            R.id.image_cardview -> intent = Intent(applicationContext, Image::class.java)
            R.id.time_cardview -> intent = Intent(applicationContext, Time::class.java)
            R.id.toast_cardview -> intent = Intent(applicationContext, Toast::class.java)
            else -> {
                intent = null
            }
        }
        if (intent != null) {
            Log.d("myOnclickListener", "${it.id}");
            intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
                .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
            startActivity(intent)
        }
    }
}

谢谢!

最佳答案

您可以删除init_MyOnClickListener并仅在定义处对其进行初始化(无论它在哪里)。除此之外,我认为您不能在不牺牲可读性的情况下将其缩短。

10-08 14:02