android - 虽然我只想选择一个,但可以选择两个单选按钮
问题描述
我正在制作一个 android 应用程序,在应用程序中可以选择一次两个单选按钮。但我只想选择一个。我应该编码什么?
public class ProfileManagement extends AppCompatActivity {
private Button update;
private EditText uname, dob, pass;
private RadioButton male, female;
private DBHelper dbHelper;
private String userId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_management);
dbHelper = new DBHelper(this);
Intent intent = getIntent();
userId = intent.getStringExtra("id");
uname = findViewById(R.id.user);
dob = findViewById(R.id.date);
pass = findViewById(R.id.word);
update = findViewById(R.id.btnUpdate);
male = findViewById(R.id.radioMale);
female = findViewById(R.id.radioFe);
ArrayList<User> list = dbHelper.readAllInfo(userId, null);
for (User u : list){
uname.setText(u.getUserName());
pass.setText(u.getPassword());
dob.setText(u.getDateOfBirth());
这是我检查单选按钮的方式。这个可以吗?
if(u.getGender() != null){
if(u.getGender().equals("Male")){
male.setChecked(true);
}
else
{
female.setChecked(true);
} } }
update.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(ProfileManagement.this, EditProfile.class);
intent.putExtra("id", userId);
startActivity(intent);
} }); } }
解决方案
像这样使用广播组:
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/text"
android:id="@+id/myRadioGroup"
android:background="#abf234"
android:checkedButton="@+id/sound" >
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/sound"
android:text="@string/Sound" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/vibration"
android:text="@string/Vibration" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/silent"
android:text="@string/Silent" />
</RadioGroup>
然后检查哪个按钮被点击了使用下面的代码:
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup rGroup, int checkedId) {
int radioBtnID = rGroup.getCheckedRadioButtonId();
View radioB = rGroup.findViewById(radioBtnID);
int position = group.indexOfChild(radioB);
}
});
推荐阅读
- django - 如何在 Django v3 中正确编写自定义用户模型和管理器?
- apollo - apollo 链接在 400 错误上重试的意外行为
- java - 对同一对象的多次引用
- rust - 从parking_lot::RwLock 返回映射数据
- php - 试图将数据传输到数据库但它们从 utf-8 变为 somting else
- azure-devops - 有没有办法将 gitignore 模板添加到 azure devops 中的新项目?
- excel - 搜索以连接列并在从另一个工作簿中选择额外数量之间,该数量应增加
- javascript - react-native-webrtc 远程流在 android 5.0.2 上不起作用
- sql - 如何提取SAS PROC SQL passthru中的记录,按日期过滤,但日期是字符串格式?
- javascript - 如何为每个 wordpress 帖子点击创建单独的弹出表单