【问题标题】:Making text Bold, Italic and Underscore with Dynamic string使用动态字符串使文本变为粗体、斜体和下划线
【发布时间】:2018-08-25 05:11:36
【问题描述】:

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

来自 API 的文本 - * 我很大胆*,也喜欢看到_我自己和_其他人。

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

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

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 标签

【问题讨论】:

  • 所以new StyleSpan(Typeface.ITALIC) 不起作用?
  • @pskink 如果我不使用粗体,它会起作用,但是当我同时使用粗体和斜体的相同过程时,我无法转换文本。对逻辑有点困惑。
  • 投了赞成票!因为它需要努力。请检查答案。
  • @W4R10CK 您是否获得更改以查看更新的答案?
  • @W4R10CK 您是否得到更改以验证解决方案?

标签: android textview android-spannable


【解决方案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-11-06
  • 2010-11-25
  • 1970-01-01
  • 1970-01-01
  • 2015-01-25
  • 1970-01-01
  • 2020-01-25
  • 2013-11-06
  • 2020-07-26
相关资源
最近更新 更多