android 如何调用使用View.generateViewId()设置了ID视图

acruukt9  于 2023-05-12  发布在  Android
关注(0)|答案(1)|浏览(99)

我有一个名为addRadioButtons的方法,它在数据库中查询用户的信用卡,然后在中显示为radiobuttons in a radiogroup in a Dialog。我将radiobuttondataSnapshot作为一对保存在HashMap中。
现在我的问题是,当用户检查单选按钮时,我不知道如何检查它是否被检查,因为我不知道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
wgx48brx

wgx48brx1#

你能不能不使用视图标签作为某种唯一的标识符?
例如:

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)
}

如果需要,可以使用val btn = radio_group.findViewWithTag<RadioButton>("a")

相关问题