The Android SDK comes with a lot of great UI widgets — two I use frequently are the radio group and the radio button. Unfortunately even in Android 4.4 KitKat, the default implementation is sort of ugly.

As developers on an open platform, we have the capability to completely customize the appearance of the radio button widget. Better yet, it’s pretty easy to do.

In this tutorial, I walk you through giving the standard radio button a face-lift. Feel free to follow along or download and import the project directly into Eclipse.

1. Create a new Android project in Eclipse. Target SDK 8 or better.

2. In the /res folder, create a new directory called drawable. Add the following XML resources.

radio_off.xml

radio_on_green.xml

radio_on_red.xml

radio_on_yellow.xml

radio_states_green.xml


radio_states_red.xml


radio_states_yellow.xml


radio_text.xml


3. In the /res/layout folder, create the layout for our demo.

activity_main.xml

4. With the bulk of the work accomplished in the XML resources, what remains is simply to wire up the radio group on change listener and echo the results to the screen via a toast message. This can be accomplished with just a few lines of code in the /src/MainActivity.java file. Notice there is no code related to the appearance or drawing of the customized widget.

MainActivity.java
package com.authorwjf.fancyradiobuttons;

import android.os.Bundle;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;
import android.app.Activity;

public class MainActivity extends Activity implements OnCheckedChangeListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((RadioGroup)findViewById(R.id.fancy_radio_group)).setOnCheckedChangeListener(this);
((RadioGroup)findViewById(R.id.standard_radio_group)).setOnCheckedChangeListener(this);
}

@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
String groupName ="";
if (group.getId() == R.id.standard_radio_group) {
groupName+="Standard radio group: ";
} else {
groupName+="Fancy radio group: ";
}
RadioButton rb = (RadioButton) findViewById(checkedId);
Toast.makeText(this, groupName+rb.getText(), Toast.LENGTH_LONG).show();
}

}

Go ahead and load the app to a device or emulator and give the radio button a few taps. It is hardly recognizable next to the default implementation and yet provides identical functionality.