Making text Bold, Italic and Underscore with Dynamic string

1.1k Views Asked by At

I'm currently trying to figure out how to make text bold, Italic or underline with dynamic string coming from API, the text which has to be bold is coming as * bold *, Italic coming as _ italic_ and underline as #underline# (Same functionality as Stackoverflow). After successful conversion of text, I want the special chars to be removed as well.

Text from API - * I am Bold* and love to see _myself and _ others too.

Expected answer - I am Bold and love to see myself and others too.

I have tried some code which does not work if I try to create italic after bold also if I try to remove special chars.

TextView t = findViewById(R.id.viewOne);
String text = "*I am Bold* and _I am Italic_ here *Bold too*";
SpannableStringBuilder b = new SpannableStringBuilder(text);
Matcher matcher = Pattern.compile(Pattern.quote("*") + "(.*?)" + Pattern.quote("*")).matcher(text);

while (matcher.find()){
  String name = matcher.group(1);
  int index = text.indexOf(name)-1;
  b.setSpan(new StyleSpan(Typeface.BOLD), index, index + name.length()+1, SpannableStringBuilder.SPAN_EXCLUSIVE_EXCLUSIVE);
}
t.setText(b);  

I don't want to use HTML tags

1

There are 1 best solutions below

1
On BEST ANSWER

Edited answer to address the edited question

Try below, you should had to pass typeface instead StyleSpan.

public class SpanTest extends Activity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        TextView test = findViewById(R.id.test);
       // String text = "*I am Bold* and _I am Italic_ here *Bold too*";
        String text = "* I am Bold* and love to see _myself and _ others too";
        CharSequence charSequence = updateSpan(text, "*", Typeface.BOLD);
        charSequence = updateSpan(charSequence, "_", Typeface.ITALIC);
        test.setText(charSequence);
    }

    private CharSequence updateSpan(CharSequence text, String delim, int typePace) {
        Pattern pattern = Pattern.compile(Pattern.quote(delim) + "(.*?)" + Pattern.quote(delim));
        SpannableStringBuilder builder = new SpannableStringBuilder(text);
        if (pattern != null) {
            Matcher matcher = pattern.matcher(text);
            int matchesSoFar = 0;
            while (matcher.find()) {
                int start = matcher.start() - (matchesSoFar * 2);
                int end = matcher.end() - (matchesSoFar * 2);
                StyleSpan span = new StyleSpan(typePace);
                builder.setSpan(span, start + 1, end - 1, 0);
                builder.delete(start, start + 1);
                builder.delete(end - 2, end - 1);
                matchesSoFar++;
            }
        }
        return builder;
    }
}

Here is the output.

enter image description here