2017-11-04 12 views
0

空のRadioGroupを含むレイアウトがあります。 (私はこれが求められているこの質問と他者との違いだと思う - 私はすでに私のレイアウトで正しい場所に空のRADIOGROUPを持っている)RadioGroupをRadioButtonsで文字列配列に取り込みます

私はstring-arrayからitem秒でこのRadioGroupを移入したいのですが私がstrings.xmlで定義したものです。

strings.xmlの配列は次のようになります。

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();が私ので、追加されました:私は、RadioButtonを作成し、TEH以下でRagioGroupに追加しようとしています

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

次のエラーが表示されますが、違いはありません。

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

明らかに問題の原因となっている行は、currencySettingRadioGroup.addView(rb);行です。

これを正しく行うにはどうすればよいですか?ただfor -loop(というよりも周りのたびに新しいRadioButtonを作成Barns52さんのコメントを1として

(私はCreate RadioButton Dynamically with String Arrayを見て、http://android.okhelp.cz/create-radiobutton-radiogroup-dynamically-android-sample/を参照したが動作するように何かを得るように見えることはできませんしました)

+0

あなたはこの行を配置する必要があり 'のRadioButton RB =新しいラジオボタン(この);'あなた 'for'ループ – Barns

+0

の内側まあ、それはそれを修正していますが、私はできません理由を理解する...これをループの中に入れることは、各ループで作成される 'rb'オブジェクトの新しいインスタンスですが、同じ名前です。 –

+0

ループの外側にその行を作成することによって、RadioButtonのインスタンスでのみ作成します。その1つのインスタンス(一意のオブジェクト)が何回かRadioGroupに追加されてエラーが発生しました。 – Barns

答えて

0

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); 
} 
関連する問題