首页 > 解决方案 > 在 kotlin 中获取选中的单选按钮

问题描述

我有以下代码,我这个错误:

一

代码

xml file

<RadioGroup
        android:id="@+id/paymentMethod"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="10dp"
        android:layout_marginTop="55dp">

        <RadioButton
            android:id="@+id/Cash"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:checked="true"
            android:text="@string/cash" />

        <RadioButton
            android:id="@+id/Online"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/online" />
</RadioGroup>

fragment

val payment_method: RadioButton = root.findViewById(R.id.paymentMethod)
val weight: EditText = root.findViewById(R.id.kilo)
val item: EditText = root.findViewById(R.id.item)
val updateButton: Button = root.findViewById(R.id.update_btn)

updateButton.setOnClickListener{
    // val mPayment = payment_method.text.toString().trim()

    val selectedRadioButtonId: Int = payment_method.checkedRadioButtonId
                                                    ^^^^^^^^^^^^^^^^^^^^
    if (selectedRadioButtonId != -1) {
        selectedRadioButton = root.findViewById(selectedRadioButtonId)
        val string: String = selectedRadioButton.text.toString()


        val mPayment = string.trim()
        val mWeight = weight.text.toString().trim()
        val mItem = item.text.toString().trim()

        Log.d("test1:", mPayment + "," + mWeight + "," + mItem)

        if(mWeight.isNotEmpty()){
            UpdateOrder(mPayment.toString(), mWeight, mItem)
        } else {
            payment_method.error = "Payment is required."
            weight.error = "Weight is required."
        }
    } else {
        Toast.makeText(context, "Select Payment.", Toast.LENGTH_SHORT).show()
    }
}

标签: androidkotlin

解决方案


嘿,您正在使用RadioGroupforpaymentMethod并将其转换为RadioButton您的代码中没有您尝试使用的方法,

val payment_method: RadioGroup = root.findViewById(R.id.paymentMethod)

推荐阅读