gpt4 book ai didi

android - 使用动态字符串将文本设为粗体、斜体和下划线

转载 作者:行者123 更新时间:2023-11-29 23:39:12 25 4
gpt4 key购买 nike

我目前正在尝试弄清楚如何使用来自 API 的动态字符串使文本粗体斜体 或下划线,必须是粗体的文本即将到来as * bold *, Italic coming as _ italic_ and underline as #underline# (Same functionality as Stackoverflow).成功转换文本后,我希望也删除特殊字符。

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.

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

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

最佳答案

Edited answer to address the edited question

试试下面,您应该传递 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;
}
}

这是输出。

enter image description here

关于android - 使用动态字符串将文本设为粗体、斜体和下划线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52014230/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com