如果一个人单击 id 为“可协商”的单选按钮,我会尝试存储“是”,否则如果单击 id“不可协商”或未选择任何内容,则存储“否”。
Kotlin 函数
private fun addProduct(): HashMap<String, String?> {
val sProductId = UUID.randomUUID().toString()
val sItemName = findViewById<EditText>(R.id.itemName).text.toString()
val sItemCategory = selectedValue
val sDescription = findViewById<EditText>(R.id.description).text.toString()
val sPrice = findViewById<EditText>(R.id.price).text.toString()
val radioGroup = findViewById<RadioGroup>(R.id.radioGroup)
var sNegotiable: String? = null
radioGroup.setOnCheckedChangeListener { group, checkedId ->
sNegotiable = if (checkedId == R.id.negotiable) {
"yes"
} else {
"no"
}
}
return hashMapOf(
"productId" to sProductId,
"itemName" to sItemName,
"itemCategory" to sItemCategory,
"description" to sDescription,
"price" to sPrice,
"negotiable" to sNegotiable
)
Xml 代码 -
<RadioGroup
android:id="@+id/radioGroup"
android:layout_width="210dp"
android:layout_height="wrap_content"
android:layout_marginBottom="40dp"
app:layout_constraintBottom_toTopOf="@+id/addProduct"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent">
<RadioButton
android:id="@+id/negotiable"
android:layout_width="match_parent"
android:layout_height="48dp"
android:text="@string/negotiable" />
<RadioButton
android:id="@+id/nonNegotiable"
android:layout_width="match_parent"
android:layout_height="48dp"
android:text="@string/non_negotiable" />
</RadioGroup>
我将其存储在 firebase firestore 中,并将 null 存储在 negotiable 中。
您在这里面临的问题是由于您的函数可能在注册单击侦听器之前返回 waaaay,并回调您。
相反,您应该努力更新您尝试使用
return hasMapOf(...)
调用更新的内容,可能以异步方式进行以避免任何并发症。
尝试将代码重构为如下所示:
interface Callback {
fun onRadioButtonClicked(values: HashMap<String, String?>)
}
private fun addProduct(callback: Callback) {
val sProductId = UUID.randomUUID().toString()
val sItemName = findViewById<EditText>(R.id.itemName).text.toString()
val sItemCategory = selectedValue
val sDescription = findViewById<EditText>(R.id.description).text.toString()
val sPrice = findViewById<EditText>(R.id.price).text.toString()
val radioGroup = findViewById<RadioGroup>(R.id.radioGroup)
var sNegotiable: String? = null
radioGroup.setOnCheckedChangeListener { group, checkedId ->
sNegotiable = if (checkedId == R.id.negotiable) {
"yes"
} else {
"no"
}
callback(
hashMapOf(
"productId" to sProductId,
"itemName" to sItemName,
"itemCategory" to sItemCategory,
"description" to sDescription,
"price" to sPrice,
"negotiable" to sNegotiable
)
)
}
}
这样,每次单击单选按钮时您都会收到通知,因此数据会发生变化,并且每次发生这种情况时您都可以采取相应的行动。当然,完成后您需要取消注册回调,以避免出现任何内存泄漏或任何其他类型的不可预见的问题!