Custom RadioButton with new XML attributes on Android

The 'conversion' RadioButtons
I am building an app to log a users Pedometer steps. It has a set of RadioButtons for different sports. By clicking on these buttons the user can choose a conversion ratio to steps. This allows them to take part in a variety of sports and still count them as 'steps' toward their goal.
I wanted it to be easy to add new sports to the list without having to do any database work, or other programming.
The way I chose was to extend RadioButton to take another XML attribute for conversion factor. This would be read from the file on construction of the button and could then be applied to any value entered.

This is what the new class looks like:

public class ConversionRadioButton extends RadioButton {
private float conversion = 1.0f;


public ConversionRadioButton(Context context, AttributeSet attrs) {
super(context, attrs);


conversion = Float.parseFloat(attrs.getAttributeValue(
"http://schemas.android.com/apk/res/ie.nolantech.plog",
"conversion"));


}


public float getConversion() {
return conversion;
}
}

I then added this to my attrs.xml file:

  <declare-styleable name="ConversionRadioButton">
        <attr format="float" name="conversion" />
    </declare-styleable>

Then the user of the button in a layout looks like this:

<ie.nolantech.plog.ConversionRadioButton
                android:id="@+id/radRun"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:checked="true"
                nt:conversion="300"
                android:text="@string/walk" />

In this case the program will award the user 300 'steps' for every minute of running that they do. If I want to add a new sport, I just need a new element like the one above with the appropriate conversion factor in place.

Remember that the new namespace (nt above) will need to be referenced in the layout file that uses it:
xmlns:nt="http://schemas.android.com/apk/res/ie.nolantech.plog"

This method of adding new xml attributes to a control is very handy and I have used it a number of times. 

References:
2. The Busy Coders Guide to Advanced Android Development - Chapter 2 covers custom component development from a number of perspectives. 

Comments

Popular posts from this blog

AutoCompleteTextView backed with data from SQLite in Android

Building a choropleth map for Irish agricultural data

Using Statistics to Hire Developers