3 回答
TA贡献1802条经验 获得超4个赞
在您获得RadioButton使用检查的 id后getCheckedRadioButtonId(),您可以将其与 2 个存在进行比较RadioButton并确定哪个是真正检查并保存到数据库:
int genderValue = 0;
if (id == R.id.radioButtonMale){
genderValue = 0;
}else{
genderValue = 1;
}
//then you can save genderValue to database
//get value from database
int genderValue = ....; //get from database
if (genderValue == 0){
radioGroup.check(R.id.radioButtonMale);
}else{
radioGroup.check(R.id.radioButtonFemale);
}
TA贡献1848条经验 获得超6个赞
你可以switch在这样的事情中使用:
RadioGroup mRadioGroup = findViewById(R.id.radioGroup);
RadioButton mRadioBtnmale = findViewById(R.id.radioButtonMale);
RadioButton mRadioBtnfemale = findViewById(R.id.radioButtonFemale);
mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId){
case R.id.radioButtonMale:
Toast.makeText(MainActivity.this,"Male selected",Toast.LENGTH_LONG).show();
break;
case R.id.radioButtonFemale:
Toast.makeText(MainActivity.this,"FeMale selected",Toast.LENGTH_LONG).show();
}
}
});
如果您想显式设置值,您可以这样做,但是您的逻辑应该决定检查和取消选中哪一个:
mRadioBtnmale.setChecked(true);
mRadioBtnmale.setChecked(false);
TA贡献1869条经验 获得超4个赞
试试这个代码--- Main.xml
<RadioGroup
android:id="@+id/radioSex"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="@+id/radioMale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/radio_male"
android:checked="true" />
<RadioButton
android:id="@+id/radioFemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/radio_female" />
</RadioGroup>
活动.java
private RadioGroup radioSexGroup;
private RadioButton radioSexButton;
private Button btnDisplay;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addListenerOnButton();
}
public void addListenerOnButton() {
radioSexGroup = (RadioGroup) findViewById(R.id.radioSex);
btnDisplay = (Button) findViewById(R.id.btnDisplay);
btnDisplay.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// get selected radio button from radioGroup
int selectedId = radioSexGroup.getCheckedRadioButtonId();
// find the radiobutton by returned id
radioSexButton = (RadioButton) findViewById(selectedId);
Toast.makeText(MyAndroidAppActivity.this, radioSexButton.getText(), Toast.LENGTH_SHORT).show();
}
});
}
添加回答
举报