Hi, trying to work out some generic code to add li...
# getting-started
b
Hi, trying to work out some generic code to add listeners to all buttons using view Bindings 'pattern'. I will put full class below but the bit that does not work is
Copy code
for (i in binding) {
    if (i is Button) i.btnPlayVideo.setOnClickListener(this)
}
I get why as you cant do a for iteration on bindings but what would be alternative code for this?
Copy code
package com.funkytwig.youtubeplayer

import android.os.Bundle
import android.os.PersistableBundle
import android.util.Log
import android.view.View
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import com.funkytwig.youtubeplayer.databinding.ActivityStandaloneBinding
import com.google.android.youtube.player.YouTubeStandalonePlayer

class StandaloneActivity : AppCompatActivity(), View.OnClickListener { // android.view.View
    private val TAG = "StandaloneActivity"
    private lateinit var binding: ActivityStandaloneBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        Log.d(TAG, "onCreate")
        super.onCreate(savedInstanceState)
        binding = ActivityStandaloneBinding.inflate(layoutInflater)
        setContentView(binding.root)

        for (i in binding) {
            if (i is Button) i.btnPlayVideo.setOnClickListener(this)
        }

        // Long form version of code
        // binding.btnPlayVideo.setOnClickListener(this)
        // binding.btnPlayPlaylist.setOnClickListener(this)
    }

    override fun onClick(view: View) { // Ctrl+I to implement interface
        TODO("Needs implementing")    
    }
}
Ben
m
You could cast the root view to a ViewGroup and loop through its children. Might need to do some recursion if the children are nested. But I would avoid this whole pattern. Making on giant method that handles all your view clicks is ugly. Just create a function for each button and manually assign click listeners to each button.
☝️ 1
b
OK, you say ugly but I much prefer generic code as it saves time and reduces errors. It's also a kind of exercise ide like to do. May give this a go later but I'm fairly new to this. I broadly understand what you mean but think I'll park this idea till I get better at Kolin.