Question

How could I create custom Spans that combined different types of spans together e.g. TypefaceSpan + RelativeSizeSpan. I want to create logical spans like "Footnote" or "Header2" that would change the text font and size.

Was it helpful?

Solution

You can apply two different spans to same portions.

SpannableStringBuilder builder = new SpannableStringBuilder("Hello there");
builder.setSpan(new TypefaceSpan("arial"), 1, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
builder.setSpan(new RelativeSizeSpan(1.5f), 1, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

EDIT: You say you're looking for a way to create aggregated Spans that combine these spans together -- so that the actual styling (e.g. TypefaceSpan or RelativeSizeSpan) can be encapsulated within logical spans (e.g. FooterSpan)

Since both TypeFaceSpan and RelativeSizeSpan are children of MetricEffectingSpan, following could be a solution:

class FooterSpan extends MetricAffectingSpan {

        MetricAffectingSpan[] spans;

        public FooterSpan(MetricAffectingSpan... spans) {
            this.spans = spans;
        }
        @Override
        public void updateMeasureState(TextPaint p) {
            for(MetricAffectingSpan span : spans) {
                span.updateMeasureState(p);
            }
        }

        @Override
        public void updateDrawState(TextPaint tp) {
            for(MetricAffectingSpan span : spans) {
                span.updateDrawState(tp);
            }
        }
    }

example usage:

builder.setSpan(new FooterSpan(new TypefaceSpan("arial"), new RelativeSizeSpan(1.5f)), 1, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

You can even write your FooterSpan in a more specialized way so that you can use it like this:

builder.setSpan(new FooterSpan("arial", 1.5f), 1, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

I think it is trivial to adopt the FooterSpan to the second case.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top