In this situation, it is better to use HasMap. HashMap are designed to quickly retrieve values ββ... Of course, in your particular case, only 4 switches are used, so you wonβt notice the difference. However, I always prefer this solution.
Create a member variable for HasMap:
Map<Integer, RadioButton> mapping = new HashMap<Integer, RadioButton>();
In the for loop, where you create your RadioButtons, add them to the hasmap:
{ ...
Finally, in your onCheckedChangeListener you can extract the RadioButton from the HashMap. Note. HashMap does not loop through all of its entries to extract the value, so it will be (slightly) faster. Of course, in this case you have to pay with memory:
radiogroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup rg, int checkedId) { String txt = ((RadioButton)mapping.get(checkedId)).getText();
source share