我有一个SpannableString对象的问题.
下面是一个简短的例子:
SpannableString spanstr = new SpannableString("Bold please!");
spanstr.setSpan(new StyleSpan(Typeface.BOLD), 0, spanstr.length(), 0);
SpannableStringBuilder sb = new SpannableStringBuilder();
sb.append(spanstr);
sb.append("\n"); // A newline
sb.append("The first line is bold. This one isn't.");
CharSequence cq = sb.subSequence(0, sb.length());
// ^There's no such method to return a SpannableString,
// so I try to return a CharSequence instead.
// And then, at last:
TextView contentView = (TextView) findViewById(R.id.some_id);
contentView.setText(cq);
Run Code Online (Sandbox Code Playgroud)
这个例子试图做的是显示:
请大胆!
第一行是粗体.这个不是.
但问题是:文本的第一行不会以粗体显示.
为什么不这样做呢?
我有一个字符串,其中包含我想要着色的特定单词.这些单词是以#开头的单词.
if(title.contains("#")){
SpannableString WordtoSpan = new SpannableString(title);
int idx = title.indexOf("#");
if (idx >= 0) {
Pattern pattern = Pattern.compile("[ ,\\.\\n]");
Matcher matcher = pattern.matcher(title);
int wordEnd = matcher.find(idx)? matcher.start() : -1;
if (wordEnd < 0) {
wordEnd = title.length();
}
WordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE),
idx,
wordEnd,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
holder.txtTitle.setText(WordtoSpan);
} else {
holder.txtTitle.setText(title);
}
Run Code Online (Sandbox Code Playgroud)
现在让我们举例说明这个字符串 粗体部分是例如彩色字.
我喜欢奶酪#burgers和#ketchup.
这是我目前的代码.我想要的是为每个#单词着色,而不仅仅是第一个单词.
恩.它会是这样的
我喜欢奶酪#burgers和#ketchup.
我想我需要循环?但是无法清楚地了解并使用xx
更新: 最新尝试.列表变为空白.
SpannableString WordtoSpan = new SpannableString(title);
int end = 0; …Run Code Online (Sandbox Code Playgroud)