How to set values for Radio button in android?

[亡魂溺海] 提交于 2019-12-24 14:36:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!