问题
I am getting the value from DB and setting it to the respective button in the below format. Is there any optimised way to do the same. All these radio buttons are inside a radio group.
if (bundlevalue.get(3).equalsIgnoreCase("Mr.")) {
rg_nametitle.check(R.id.mr);
} else if (bundlevalue.get(3).equalsIgnoreCase("Mrs.")) {
rg_nametitle.check(R.id.mrs);
} else if (bundlevalue.get(3).equalsIgnoreCase("Ms.")) {
rg_nametitle.check(R.id.ms);
} else {
rg_nametitle.check(R.id.messrs);
}
回答1:
You can try as follows...
String value = bundlevalue.get(3)
Resources res = getResources();
if (value.equalsIgnoreCase("Mr.") || value.equalsIgnoreCase("Mrs.") || value.equalsIgnoreCase("Ms.")) {
String[] splitedValue = value.toLowerCase ().split(".");
int id = res.getIdentifier(splitedValue[0], "id", getContext().getPackageName());
rg_nametitle.check(id);
} else {
rg_nametitle.check(R.id.messrs);
}
回答2:
In case if you use XML
attribute like this :
<RadioGroup
...
...
android:checkedButton="@+id/IdOfTheRadioButtonInsideThatTobeChecked"
... >....</RadioGroup>
or you can use switch-case
statement like this :
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radio_pirates:
if (checked)
// Pirates are the best
break;
case R.id.radio_ninjas:
if (checked)
// Ninjas rule
break;
}
}
回答3:
Use switch
statement. Although, there is nothing big difference in using if-else
or switch
, you can go ahead with whichever is more readable to you.
public enum Title
{
Mr, Mrs, Ms;
}
String title = bundlevalue.get(3).equalsIgnoreCase("Mr.");
switch(Title.valueOf(title)) {
case Mr:
rg_nametitle.check(R.id.mr);
break;
case Ms:
rg_nametitle.check(R.id.ms);
break;
case Mrs:
rg_nametitle.check(R.id.mrs);
break;
default:
break;
}
来源:https://stackoverflow.com/questions/22828675/how-to-set-values-for-radio-button-in-android