首页 > 解决方案 > Android 富文本 Mark Down

问题描述

我正在寻找有关使用 Mark Down 创建富文本的库或优化示例。

例如,要转的东西:

1 - *粗体* ->粗体

2 - _斜体_ ->斜体

长示例:

3 - _Hello_ *World* ->你好 世界

等等。

我见过很多应用程序都在使用它,比如 Discord、Whatsapp、Skype。

我做过类似的事情,但我知道它没有优化并且可能导致运行时错误。

标签: javaandroidtextformatting

解决方案


您不需要任何额外的库...

只是看看android.text.SpannableStringBuilder...

这将允许您获得文本功能,例如:

  • 让它变大
  • 大胆的
  • 强调
  • 斜体
  • 删除线
  • 有色
  • 突出显示
  • 显示为上标
  • 显示为下标
  • 显示为链接
  • 使其可点击。

这里有一个关于如何在 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);        

推荐阅读