代码之家  ›  专栏  ›  技术社区  ›  mafortis

在kotlin中获取选定单选按钮

  •  0
  • mafortis  · 技术社区  · 3 年前

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

    one

    代码

    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()
        }
    }
    
    1 回复  |  直到 3 年前
        1
  •  2
  •   Rajan Kali    3 年前

    嘿,你在用 RadioGroup 对于 paymentMethod 并将其铸造成 RadioButton 在没有您尝试使用的方法的代码中,

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