要解决这个问题,首先,您必须创建一个包含两个单选按钮的布局:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RadioGroup
android:id="@+id/radioGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent">
<RadioButton
android:id="@+id/yesRadioButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Yes"/>
<RadioButton
android:id="@+id/noRadioButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="No"/>
</RadioGroup>
</androidx.constraintlayout.widget.ConstraintLayout>
然后在你的活动中,你必须通过 id 找到它们并附加一个实时监听器。假设您的 Firestore 架构如下所示:
Firestore-root
|
--- users
|
--- $uid
|
--- participate: true
|
--- //other fields
这是代码:
将它们定义为类的成员(全局变量):
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
FirebaseFirestore db = FirebaseFirestore.getInstance();
DocumentReference uidRef = db.collection("users").document(uid);
在onCreate里面添加:
RadioButton yesRadioButton = findViewById(R.id.yesRadioButton);
RadioButton noRadioButton = findViewById(R.id.noRadioButton);
uidRef.addSnapshotListener(new EventListener<DocumentSnapshot>() {
@Override
public void onEvent(@Nullable DocumentSnapshot snapshot, @Nullable FirebaseFirestoreException e) {
if (e != null) {
Log.w(TAG, "Listen failed.", e);
return;
}
if (snapshot != null && snapshot.exists()) {
Boolean participate = snapshot.getBoolean("participate");
if(participate != null) {
if (participate) {
yesRadioButton.setChecked(true);
} else {
noRadioButton.setChecked(true);
}
}
}
}
});
以下是在每个单选按钮上附加点击侦听器的代码:
yesRadioButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (yesRadioButton.isChecked()) {
updateParticipate(true);
}
}
});
noRadioButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (noRadioButton.isChecked()) {
updateParticipate(false);
}
}
});
这是负责更新的方法:
void updateParticipate(boolean participate) {
Map<String, Object> update = new HashMap<>();
update.put("participate", participate);
uidRef.update(update).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
Toast.makeText(getApplicationContext(), "Updated: " + participate, Toast.LENGTH_SHORT).show();
}
});
}