1

It's fine? :D

I have an API PHP that receives html text replaced by string [tag] tags and my Android app needs to replace this tags of text by Spannable strings.

I have a problem with replace string tags of [strong], [br], [p], [i] to SpannableString and to apprimorate the content text.

Not all text is overwritten correctly. Some [strong] tags, for example, still remain there, other times the text is repeated, rather than overlapping.

My Activity receives that:

...

SpannableStringBuilder parseContent = new StringTagParserHelper(tagPost.getContent())
    .addMultipleStyle();

contentView.setText(parseContent);

My String parser classe is:

public class StringTagParserHelper {

    private static String rawText;
    private SpannableStringBuilder spannableContent;

    public StringTagParserHelper(String text) {
        rawText = text;
    }

    /**
     * @return
     */
    public SpannableStringBuilder addMultipleStyle() {
        spannableContent = new SpannableStringBuilder(rawText);

        cleanTags("strong");

        return spannableContent;
    }

    private void cleanTags(String tag) {
        Pattern pattern = Pattern.compile(tag + "\\](.+?)\\[/" + tag);
        Matcher matcher = pattern.matcher(rawText);

        while (matcher.find()) {
            Log.d("PARSE", String.valueOf(matcher.group(1)));

            String _internal = matcher.group(1);
            int start = matcher.start();
            int end = matcher.end();

            if (tag.equals("strong")) {
                Spannable spanText = new SpannableString(_internal);
                spanText.setSpan(
                        new StyleSpan(Typeface.BOLD), 0, _internal.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                );

                spannableContent.replace(start, end, spanText);
            }

            if (tag.equals("br")) {
                //
            }

        }
    }

.

[EDIT]

Added 2 screenshots.

  • One with bold text and spannable replace of spanText

enter image description here

  • another without style and spannable replace _internal string.

enter image description here

The line of Log.d() receives the list of raw string text without tags.

Log.d("PARSE", String.valueOf(matcher.group(1)));

Please, help me, guys!

References:

Android TextView format multiple words

https://stackoverflow.com/a/6560685/3332734

https://stackoverflow.com/a/32369427/3332734

Android. Replace * character from String

Community
  • 1
  • 1
Francis Rodrigues
  • 1,470
  • 4
  • 25
  • 61

0 Answers0