2

我目前正在尝试弄清楚如何使用来自API的动态字符串使文本变为粗体斜体或下划线,必须为粗体的文本为*粗体*,斜体为_斜体,下划线为#underline#(与 Stackoverflow 相同的功能)。成功转换文本后,我也希望删除特殊字符。

来自 API 的文本 - *我很大胆*,也喜欢看到 _myself 和 _ others。

预期的答案 -我很大胆,也喜欢看到自己和他人。

如果我尝试在粗体之后创建斜体,如果我尝试删除特殊字符,我已经尝试了一些不起作用的代码。

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);  

我不想使用 HTML 标签

4

1 回答 1

1

编辑答案以解决已编辑的问题

试试下面,你应该改为typeface通过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;
    }
}

这是输出。

在此处输入图像描述

于 2018-08-25T07:06:58.707 回答