How to replace string tag in spannableStringBuilder

  • Replies:0
  • OpenNot stickiedUnanswered
  • Forum posts: 1

Nov 28, 2016 10:13:17 PM via Website

Hi guys! 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 SpannableStringand 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")) {
                    //
                }

            }
        }

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:

stackoverflow.com/questions/9973764/android-textview-format-multiple-words
stackoverflow.com/a/6560685/3332734
stackoverflow.com/a/32369427/3332734
stackoverflow.com/questions/14590710/android-replace-character-from-string