【问题标题】:Populate a RadioGroup with RadioButtons from a string-array使用字符串数组中的 RadioButtons 填充 RadioGroup
【发布时间】:2018-04-17 07:30:30
【问题描述】:

我的布局包含一个空的RadioGroup。 (我认为这是这个问题与其他问题之间的区别 - 我已经在我的布局中的正确位置有空的 RadioGroup)

我想用我在strings.xml 中定义的string-array 中的items 填充这个RadioGroup

strings.xml 中的数组如下所示:

<string-array name="currency_symbols">
    <item>$ - Dollar</item>
    <item>€ - Euro</item>
    <item>£ - Pound</item>
    <item>¥ - Yen</item>
    <item># - Other</item>
</string-array>

然后我尝试创建一个RadioButton 并将其添加到 RagioGroup 中,如下所示:

RadioGroup currencySettingRadioGroup = (RadioGroup) settings_dialog.findViewById(R.id.rg_currency_symbol);
currencySettingRadioGroup.removeAllViews();

RadioButton rb = new RadioButton(this);
String[] currency_symbols_options_array = getResources().getStringArray(R.array.currency_symbols);
for ( String this_currency_option: currency_symbols_options_array ) {
    rb.setText(this_currency_option);
    currencySettingRadioGroup.addView(rb);
}

添加了currencySettingRadioGroup.removeAllViews();,因为我收到以下错误,但这没有什么区别:

java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

显然导致问题的行是currencySettingRadioGroup.addView(rb); 行...

我该如何正确地做到这一点?

(我查看了Create RadioButton Dynamically with String Array 和引用的http://android.okhelp.cz/create-radiobutton-radiogroup-dynamically-android-sample/,但似乎没有任何工作)

【问题讨论】:

  • 您需要将此行 RadioButton rb = new RadioButton(this); 放入您的 for 循环中
  • 嗯,已经解决了,但我不知道为什么......通过将它放在循环中是在每个循环上创建的 rb 对象的新实例,但名称相同?
  • 通过将该行放在循环之外,您只在 RadioButton 的实例上创建。并且该实例(一个唯一对象)被多次添加到 RadioGroup 中,从而导致错误。
  • 胖僧 :: 你写了“但是同名?” .你的意思是文本是一样的吗?例如。 “$ - Dollar”五次??
  • 不,我的意思是每次循环我们都会创建一个名为rb的新单选按钮对象。

标签: java android radio-button radio-group


【解决方案1】:

根据 Barns52 的评论,每次在 for-loop 周围创建一个新的 RadioButton(而不是在 for-loop 开始之前只创建一次)可以解决此问题。

工作代码如下:

RadioGroup currencySettingRadioGroup = (RadioGroup) settings_dialog.findViewById(R.id.rg_currency_symbol);

String[] currency_symbols_options_array = getResources().getStringArray(R.array.currency_symbols);
for ( String this_currency_option: currency_symbols_options_array ) {
    RadioButton rb = new RadioButton(this);
    rb.setText(this_currency_option);
    currencySettingRadioGroup.addView(rb);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-03
    • 2017-02-02
    • 2015-05-10
    • 1970-01-01
    • 2015-11-03
    • 2011-09-07
    • 1970-01-01
    相关资源
    最近更新 更多