GreenDroid has a great widget called a SegmentedBar where an app can display information in different sections much like how tabs work but they all get loaded at one time.

From the developer of GreenDroid, he describes a SegmentedBar as a bunch of segments where each segment has an indicator that can be on or off depending on its current state (checked or not). Once you are tapping a segment, the associated view is displayed.

Each of these segments is represented by a CheckBox widget. There came a point wherein I wanted my app to show only images without any text. The problem was that even if I managed to center the default checkbox image (the one with a checkmark), it did not center itself when I set a custom drawable image like the ones below.

There was always an extra space on the right that made the drawable images not aligned to the center. So how did I manage to make the custom drawables aligned to the center (pictured above)? By creating my own custom CheckBox class.

I also extended GreenDroid classes related to the SegmentedBar (no sense modifying the source in GreenDroid in case of new updates, right?) to cater to the XML layout file of the CheckBox widget.

Here is the segmented bar background 9-patch image that I trimmed. Save it as segment_bg.9.png.

Here is a sample drawable state list on for a checkbox. Make sure you place this in the drawables folder.

Here is the segmented XML file that covers the CheckBox. I purposely placed another LinearLayout layer on top of the CheckBox widget to center it within the layout.

To make this work, here is a sample code that assigns a drawable to each segment. For this sample, I have 6 segments in total.

If you wondered why the index is in increments of even numbers, it is because the odd numbers represent the divider drawable image that divides each segment.

So there you have it. It took me quite some time to figure this out. I had to dig into the CompoundButton class to see what methods I could override to make the icons of segments without text aligned to the center.

Related Posts Plugin for WordPress, Blogger...