Search code examples
androidkotlinandroid-viewradio-group

how to call a view that had it's id set with View.generateViewId()


i have a method called addRadioButtons that queries my database for the user's credits cards, and then display in as radiobuttons in a radiogroup in a Dialog. I save the radiobutton, and the dataSnapshot as a pair in a HashMap.

Now my problem is, when a user checks a radiobutton, i have no idea how to check if it's been checked because i dont know the id.

addRadioButtons()

if(dataSnapshot.exists()){
    val ll = RadioGroup(context)
    for (source: DataSnapshot in dataSnapshot.children) {
        val last4 = source.child("last4").value.toString()
        val brand = source.child("brand").value.toString()

        val rdbtn = RadioButton(context)
        rdbtn.id = View.generateViewId()

        val textStr = "$brand ************$last4"
        rdbtn.text = textStr
        ll.addView(rdbtn)
        radioButtonMap.put(rdbtn, source)
   }
   radiogrp.addView(ll)
}

openDialog()

private fun openDialog() {
    val dialog = Dialog(this.context!!)

    dialog.setContentView(R.layout.stripe_layout)
    val lp : WindowManager.LayoutParams = WindowManager.LayoutParams().apply {
        copyFrom(dialog.window?.attributes)
        width = WindowManager.LayoutParams.MATCH_PARENT
        height = WindowManager.LayoutParams.WRAP_CONTENT
    }

    radiogrp = dialog.findViewById<View>(R.id.radio_group) as RadioGroup
    addRadioButtons()
    //HOW DO I USE THIS?!?
    //radiogrp.setOnCheckedChangeListener

Solution

  • can you not use View tags for some sort of unique identifier?

    E.g:

    val rd = RadioGroup(context)
    val records = listOf(
        "a" to "some record",
        "b" to "some record",
        "c" to "some record"
    )
    for (record in records) {
        val btn = RadioButton(context)
        btn.tag = record.first
        btn.id = View.generateViewId()
        rd.addView(btn)
    }
    radio_group.addView(rd)
    rd.setOnCheckedChangeListener { _, checkedId ->
        val btn = radio_group.findViewById<RadioButton>(checkedId)
        println(btn.tag)
    }
    

    So you can do val btn = radio_group.findViewWithTag<RadioButton>("a") if needed be.