Tuesday, November 18, 2014

Android Stacked Fractions

I read about a small new feature on TextView in Android Lollipop:

I never heard of CSS font-feature-settings, but a quick internet search led me to a sandbox, where I can play with OpenType font features such as kerning and ligature. Not particularly exciting, but then I scrolled down the list and saw fractions. I experimented with different settings and came up with this:

Stacked fractions! Let's put that in a TextView.

First, I need a font that supports afrc. I chose Nutso2, an Apache 2 licensed font.

I first tried to set font settings on the whole TextView:

Typeface typeface = Typeface.createFromAsset(
    getAssets(), "Nutso2.otf");
textView.setTypeface(typeface);
textView.setText("1/2 2/5");
textView.setFontFeatureSettings("afrc");

Looks good. But then I want to display one and a half. If I set text as "1 1/2" there is a space, and if I use "11/2" it shows eleven over two. What to do?

I went back to the Nutso project for their demo page:

1<span class="afrc">1/2</span>

HTML with span, eh? Why yes, I can do that in Android! We'll need a TagHandler with a custom Span.

1<afrc>1/2</afrc>

The TagHandler is called twice: at the start of the span, again at the end. We mark the beginning of the tag with a Spannable.SPAN_MARK_MARK so we can retrieve it at the end of the span. With that we have the start and end positions of our stacked fraction, and we can apply our FractionSpan to activate the afrc font feature settings.

Now we have mixed fractions, no space. Yay!

Source: https://github.com/chiuki/advanced-textview (FractionActivity)

To hear about this and other cool TextView tricks, come to my Advanced Android TextView talk at AnDevCon this Friday!

No comments:

Post a Comment

Inline coding questions will not be answsered. Instead, ask on StackOverflow and put the link in the comment.