androidhtmlspanned

How to split up a SpannableStringBuilder while keeping its formating?


I am working on an android project that involves parsing some HTML (parsed by Jsoup) into a SpannableStringBuilder class.

However, I need this SpannableStringBuilder class to be divided up by each new line character into a List once it is done parsing, while keeping its formatting.

Such that a spanned text of

{"I am a spanned text,\n hear me roar"}

would turn into

{ "I am a spanned text," "hear me roar" }

I am fairly new to developing on Android, and could not find anything in the documentation about spitting spans or even getting a listing of all formatting on a spanned class to build my own. So any help is much appreciated.


Solution

  • I managed to figure this out on my own, after looking into the method that pskink suggested.

    My solution to this was

    @Override
        public List<Spanned> parse() {
            List<Spanned> spans = new ArrayList<Spanned>();
            Spannable unsegmented = (Spannable) Html.fromHtml(base.html(), null, new ReaderTagHandler());
            //Set ColorSpan because it defaults to white text color
            unsegmented.setSpan(new ForegroundColorSpan(Color.BLACK), 0, unsegmented.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
    
            //get locations of '/n'
            Stack<Integer> loc = getNewLineLocations(unsegmented);
            loc.push(unsegmented.length());
    
            //divides up a span by each new line character position in loc
            while (!loc.isEmpty()) {
                Integer end = loc.pop();
                Integer start = loc.isEmpty() ? 0 : loc.peek();
    
                spans.add(0,(Spanned) unsegmented.subSequence(start, end));
             }
    
            return spans;
        }
    
        private Stack<Integer> getNewLineLocations(Spanned unsegmented) {
            Stack<Integer> loc = new Stack<>();
            String string = unsegmented.toString();
            int next = string.indexOf('\n');
            while (next > 0) {
                //avoid chains of newline characters
                if (string.charAt(next - 1) != '\n') {
                    loc.push(next);
                    next = string.indexOf('\n', loc.peek() + 1);
                } else {
                    next = string.indexOf('\n', next + 1);
                }
                if (next >= string.length()) next = -1;
            }
            return loc;
        }