简体   繁体   中英

Android rich text Mark Down

I'm looking for a library or optimized examples on using Mark Down to create Rich Text.

For example, something to turn:

1 - *Bold* -> Bold

2 - _Italic_ -> Italic

Long example:

3 - _Hello_ *World* -> Hello World

And so on.

I've seen many apps use it, like Discord, Whatsapp, Skype.

I've done something similar, but I know it's not optimized and can lead to runtime errors.

You don't need any extra library...

Just have a look into android.text.SpannableStringBuilder ...

This will allow you to get text features like:

  • Make it larger
  • Bold
  • Underline
  • Italicize
  • Strike-through
  • Colored
  • Highlighted
  • Show as superscript
  • Show as subscript
  • Show as a link
  • Make it clickable.

Here you have an example on how to apply a Bold style on a word in a TextView :

String text = "This is an example with a Bold word...";  

// Initialize a new SpannableStringBuilder instance
SpannableStringBuilder strb = new SpannableStringBuilder(text);

// Initialize a new StyleSpan to display bold text
StyleSpan bSpan = new StyleSpan(Typeface.BOLD);

// The index where to start applying the Bold Span
int idx = text.indexOf("Bold");

strb.setSpan(
                bSpan, // Span to add
                idx, // Start of the span
                idx + 4, // End of the span 
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        );

// Display the spannable text to yourTextView
yourTextView.setText(ssBuilder);        
SpannableStringBuilder str = new SpannableStringBuilder("Your awesome text");
str.setSpan(new android.text.style.StyleSpan(android.graphics.Typeface.BOLD), start_int, end_int, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
TextView tv=new TextView(context);
tv.setText(str);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM