[英]How to set values for Radio button in android?
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);
}
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);
}
In case if you use XML
attribute like this : 如果您使用这样的XML
属性:
<RadioGroup
...
...
android:checkedButton="@+id/IdOfTheRadioButtonInsideThatTobeChecked"
... >....</RadioGroup>
or you can use switch-case
statement like this : 或者您可以使用switch-case
语句,例如:
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;
}
}
Use switch
statement. 使用switch
语句。 Although, there is nothing big difference in using if-else
or switch
, you can go ahead with whichever is more readable to you. 尽管使用if-else
或switch
没有什么大的不同,但是您可以继续阅读更容易理解的内容。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.