Set Styles programmatically in Android

Styles in Android are a very useful kind of resources which allow us to easily configure a set of components. Styles can be created as resources in an xml file. Styles can also be set to a component in its xml declaration, but sometimes it is necessary to set the styles programmatically.
Suppose we have a big list of locations to be added as radio buttons. The easiest way to add them is doing it programmatically. When creating a new radio button, the first approach would be to use the “new RadioButton” sentence. The constructor receives the style ID as one of its parameters.

// Get the list
String[] locationArray = getResources().getStringArray(R.array.location);

RadioGroup radioGroupLocations = (RadioGroup) findViewById(R.id.filtro_radioGroup_locations);
RadioButton radioButtonLocation;

// For each location, create a radio button
for (String string : locationArray) {
   radioButtonLocation = new RadioButton(this, null, R.style.RadioButton_style);
   radioButtonLocation.setText(string);
   
   // Different IDs to get the expected behaviour as radio group
   radioButtonLocation.setId(radioGroupLocations.getChildCount());  

   // Add the button to the group 
   radioGroupLocations.addView(provincia);
}

The result is not the expected one. Every radio button should have the style of the first one.

Radio buttons before

The solution is not to use the constructor, but to use the “getLayoutInflater” method. This solution requires to create a layout with just the radio button as its content (template_radiobutton.xml):

<?xml version="1.0" encoding="utf-8"?>
<RadioButton style="@style/RadioButton_style" />

The code is now:

// Get the list
String[] locationArray = getResources().getStringArray(R.array.location);

RadioGroup radioGroupLocations = (RadioGroup) findViewById(R.id.filtro_radioGroup_locations);
RadioButton radioButtonLocation;

// For each location, create a radio button
for (String string : locationArray) {
   radioButtonLocation = (RadioButton) getLayoutInflater().inflate(R.layout.template_radiobutton, null);
   radioButtonLocation.setText(string);

   // Different IDs to get the expected behaviour as radio group
   radioButtonLocation.setId(radioGroupLocations.getChildCount());
   
   // Add the button to the group 
   radioGroupLocations.addView(provincia);
}

And the result:

Radio buttons after

Share Button

5 Comments

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload the CAPTCHA.