Set text of Radio Buttons in Radio Group via an array instead of separate strings in xml layout

StackOverflow https://stackoverflow.com/questions/23426507

  •  14-07-2023
  •  | 
  •  

سؤال

I would like to use an array instead of separate strings for radio buttons members of a radio group.

This necessarily comes out of logic that I need later. However I couldn't find a way to do it in the predefined layout, and doing it programmatic seems like an unnecessary overhead both in logic and efficiency:

I would have to get the String[], convert it to a array, then iterate over the radio group (creating an object every time) :

    RadioGroup rg = (RadioGroup) frg_view.findViewById(R.id.rg1);
    ArrayList<String> arrayText = new ArrayList<>();
    String[] text = getResources().getStringArray(R.array.arr1);
    Collections.addAll(arrayText, text);


    for (int i = 0; i < rg.getChildCount(); i++) {
        RadioButton rb = (RadioButton) rb.getChildAt(i);
        rb.setText(arrayText.get(i));

    }

Is there a way to do it smarter and directly in the layout file? Otherwise the other option I've came up is just to define the strings for those radiogroups twice - once as separate IDs for the layout file and a second time as arrays for the program logic

هل كانت مفيدة؟

المحلول

I think you can define the strings separately, then do this in res/values/arrays.xml

<resources>
    <string-array>
        <item>@string/radio_button1</item>
        <item>@string/radio_button2</item>
        <!-- etc -->
    </string-array>
</resources>

It's not great, but at least you don't define the strings twice.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top