Skip to content Skip to sidebar Skip to footer

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 di

Solution 1:

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

My solution to this was

@Override
    publicList<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 locwhile (!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<>();
        Stringstring = unsegmented.toString();
        int next = string.indexOf('\n');
        while (next > 0) {
            //avoid chains of newline charactersif (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;
    }

Post a Comment for "How To Split Up A Spannablestringbuilder While Keeping Its Formating?"