使用单个监听器管理多个视图

问题描述 投票:0回答:1

知道如何修复这个可怕的代码,以便单个触摸监听器可以处理所有点击吗?

        // Devices
        val devices = DeviceDAO(context).getDevicesByType(2)
        adapter = ShipDevicesAdapter(devices)
        binding.shipDevicesRecyclerView.layoutManager = LinearLayoutManager(context)
        binding.shipDevicesRecyclerView.adapter = adapter

        var engine = 0
        binding.engineLayout.engineView1.setOnClickListener {
            binding.shipDevicesRecyclerView.visibility = View.VISIBLE
            engine = 1
        }

        binding.engineLayout.engineView2.setOnClickListener {
            binding.shipDevicesRecyclerView.visibility = View.VISIBLE
            engine = 2
        }

        binding.engineLayout.engineView3.setOnClickListener {
            binding.shipDevicesRecyclerView.visibility = View.VISIBLE
            engine = 3
        }

        binding.engineLayout.engineView4.setOnClickListener {
            binding.shipDevicesRecyclerView.visibility = View.VISIBLE
            engine = 4
        }

        adapter.setOnItemClickListener {
            val resId = Game.getResId(it.image, R.drawable::class.java)
            when(engine){
                1 -> binding.engineLayout.engineView1.setImageResource(resId)
                2 -> binding.engineLayout.engineView2.setImageResource(resId)
                3 -> binding.engineLayout.engineView3.setImageResource(resId)
                4 -> binding.engineLayout.engineView4.setImageResource(resId)
            }
            binding.shipDevicesRecyclerView.visibility = View.GONE
        }

我尝试使用view.id收集视图id,也使用view.current focus,也使用R.id.engineView资源,但我不知道如何收集它。代码位于片段中,而不是活动中。

kotlin android-fragments events listener adapter
1个回答
0
投票

我创建一个包含所有视图的数组,然后返回选定的视图,我不知道它是否是最正确的,但它似乎有效

    private lateinit var v: ImageView

   // Code inside onCreateView
    val devices = DeviceDAO(context).getDevicesByTechLearned()
    adapter = DevicesAdapter(devices, context)
    binding.shipDevicesRecyclerView.layoutManager = LinearLayoutManager(context)
    binding.shipDevicesRecyclerView.adapter = adapter

    viewListener()

    adapter.setOnItemClickListener {
        val resId = Game.getResId(it.image, R.drawable::class.java)
        v.setImageResource(resId)
        binding.shipDevicesRecyclerView.visibility = View.GONE
    }

private fun viewListener() {
    val engineView1 = binding.devicesLayout.engineView1
    val engineView2 = binding.devicesLayout.engineView2
    val engineView3 = binding.devicesLayout.engineView3
    val engineView4 = binding.devicesLayout.engineView4

    val engineView = arrayListOf(
        engineView1, engineView2, engineView3, engineView4,
    )

    engineView.forEach { v ->
        v.setOnClickListener {
            viewSelected(v)
        }
    }
}

private fun viewSelected(view: ImageView): ImageView {
    binding.shipDevicesRecyclerView.visibility = View.VISIBLE
    v = view
    return v
}
© www.soinside.com 2019 - 2024. All rights reserved.