Search code examples
androidspannable

How to define order (setPriority) of Spannable in Android


I have few overlapping spans within SpannableStringBuilder. I would like to define order in which they will be implemented to Text. Spannable have int flags

int SPAN_PRIORITY = 16711680;
int SPAN_PRIORITY_SHIFT = 16;

How can I use them? How many levels Spannable priority have? What is the default one?


Solution

  • To define priority you have to utilize bits magic:

    int priority = 123; // Should be in range [0..255].
    int spanFlags = 0;
    // ...
    // Cleaning up priority bits.
    spanFlags &= ~Spannable.SPAN_PRIORITY; 
    // Injecting priority bits.
    spanFlags |= (priority << Spannable.SPAN_PRIORITY_SHIFT) & Spannable.SPAN_PRIORITY;
    // ...
    sb.setSpan(what, start, end, spanFlags);