2

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

W4R10CK
  • 5,502
  • 2
  • 19
  • 30

1 Answers1

2

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

Krishna Sharma
  • 2,828
  • 1
  • 12
  • 23