AnnotationSpan / Rialto / Spans / Text

Rialto – Advanced Usage

A new Android text styling library based upon Annotation Spans. Rialto enables you to provide consistent text formatting throughout your app by using annotations in your string resources. In this article we’ll look a little deeper in to some of the more advanced aspects of using Rialto. Although even the advanced stuff isn’t particularly complex!

One possible complexity when using annotation spans is that it is not possible to use the same key more than once in any specific annotation instance. In other words, if you have <annotation format="bold" format="underline">...</annotation> within a string resource you’ll get an error because XML does not support multiple attributes of the same name. One solution to this is to nest annotation elements one inside another, but this ends up becoming rather verbose and will bloat your string resources making them difficult to read.

The mechanism that Rialto uses to allow multiple span types to be combined is that it allows you to set multiple span factories for any given key/value pair. The easiest way to demonstrate this is with an example:

class MainActivity : RialtoActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        registerSpanFactory("format", "bold") { StyleSpan(Typeface.BOLD) }
        registerSpanFactory("format", "italic") { StyleSpan(Typeface.ITALIC) }
        registerSpanFactory("format", "bold_underline") { StyleSpan(Typeface.BOLD) }
        registerSpanFactory("format", "bold_underline") { UnderlineSpan() }
        setContentView(R.layout.activity_main)
    }
}

Here we add two separate span factories for the key “format” with the value “bold_underline“. When an annotation of <annotation format="bold_underline">...</annotation> is encountered within a string resource, then both the bold and underline spans will be applied:

In the previous article I mentioned that it would become apparent why it is better to apply formatting such as bold and italic using annotations spans rather than <b> and <i> and this is why. While we could achieve bold underline using <b><u>…</u></b> it would make it much harder to combine these kinds of formats with others which are not supported by the HTML style formatting. However if we use a consistent approach throughout our app, then we can easily combine formats as per this example.

The other thing worth covering is how to use Rialto in cases where extending RialtoActivity is not possible. Your Activity must implement the RialtoDelegate interface, and needs to construct a RialtoDelegate instance to which it delegates all of the required behaviour:

class MainActivity : AppCompatActivity(), RialtoDelegate {
    private lateinit var delegate: RialtoDelegate

    override fun registerSpanFactory(key: String, value: String, creator: () -> Any) {
        delegate.registerSpanFactory(key, value, creator)
    }

    override fun processAnnotations(text: CharSequence?): CharSequence? =
            delegate.processAnnotations(text)

    override fun onCreate(savedInstanceState: Bundle?) {
        delegate = RialtoDelegateImpl(this)

        super.onCreate(savedInstanceState)
        registerSpanFactory("format", "bold") { StyleSpan(Typeface.BOLD) }
        registerSpanFactory("format", "italic") { StyleSpan(Typeface.ITALIC) }
        setContentView(R.layout.activity_main)
    }
}

Implementing RialtoDelegate requires the methods registerSpanFactory(key: String, value: String, creator: () -> Any) and processAnnotations(text: CharSequence?): CharSequence? to be implemented. All we need to do here is create an instance of RialtoDelegateImpl(this) which we do in onCreate() and then we can delegate both of these methods to the RialtoDelegateImpl instance. It is important to initialise this before the call to super.onCreate() otherwise Rialto will not initialise correctly, and no processing of annotation in string resources will be performed.

We can also do this from Java in much the same way:

public class MainActivity extends AppCompatActivity implements RialtoDelegate {

    private RialtoDelegate delegate = null;

    @Override
    public void registerSpanFactory(@NotNull String key, @NotNull String value, @NotNull Function0<?> creator) {
        delegate.registerSpanFactory(key, value, creator);
    }

    @Override
    public CharSequence processAnnotations(CharSequence text) {
        return delegate.processAnnotations(text);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        delegate = new RialtoDelegateImpl(this);

        super.onCreate(savedInstanceState);

        registerSpanFactory("format", "bold", new Function0<CharacterStyle>() {
            @Override
            public CharacterStyle invoke() {
                return new StyleSpan(Typeface.BOLD);
            }
        });
        registerSpanFactory("format", "italic", () -> new StyleSpan(Typeface.ITALIC));
        setContentView(R.layout.activity_main);
    }
}

The important differences here are with the method signatures of the methods from RialtoDelegate that we need to override. However, if you allow Android Studio to generate the method stubs for you once you have added implements RialtoDelegate to the MainActivity class, then you can’t go far wrong.

One last thing worth mentioning is that if you are using Rialto from Java there are a couple of things worth bearing in mind. Firstly, the mechanism for calling registerSpanFactory() will vary depending on whether you are using Java 7 or Java 8:

If you are using Java 7 then you will need to create a Function0 instance as the third argument to registerSpanFactory():

registerSpanFactory("format", "bold", new Function0&lt;CharacterStyle&gt;() {
    @Override
    public CharacterStyle invoke() {
        return new StyleSpan(Typeface.BOLD);
    }
});

However if you are using Java 8 (or Retrolambda) then you can use a lambda instead:

registerSpanFactory("format", "italic", () -> new StyleSpan(Typeface.ITALIC));

The second thing that you will need to do is add the Kotlin standard library as a dependency to your project:

dependencies {
    ...
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    ...
}

Rialto is written 100% in Kotlin, but can be used quite easily from Java. The only pre-requisite is that the Kotlin standard library is needed because it contains the Function0 class that is used for Java compatibility of Kotlin lambdas.

One final thing worth noting is that when Rialto does its stuff, it adds spans to the string resource, but does not remove the annotation spans as it goes. The reasoning behind this is that some use-cases may require some further processing of those annotations, and removing them would prevent this. Also, it is worth remembering that on a Spanned instance the individual Span objects are relatively small, so keeping the Annotation instances is not going to be a major memory issue.

Rialto is really quite simple to use and the API surface is really quite small. Internally it isn’t a particularly large or complex library, it’s power is based upon creating the registry of span factories which apply the relevant spans whenever specific annotations are encountered.

Rialto is available on JCenter, and the source code is available here.

© 2018, Mark Allison. All rights reserved.

Copyright © 2018 Styling Android. All Rights Reserved.
Information about how to reuse or republish this work may be available at http://blog.stylingandroid.com/license-information.

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.