我一直在使用此处显示的代码:http://www.androidengineer.com/2010/08/easy-method-for-formatting-android.html
我想以几种不同的方式格式化几个不同的单词。例如:段落中的5个单词为红色,6个不同的单词为蓝色等。
我已经能够在for循环中使用代码,但我无法弄清楚如何使用while而不是for。我怀疑它与以某种方式重置开始和结束实例变量有关,但同样没有成功。
这是代码,感谢您的帮助。
public class TextFormatter extends Activity {
private int mFormatCounter;
public void formatText(TextView tV) {
CharSequence text = tV.getText();
for (int i = 0; i < 10; i++) {
switch (mFormatCounter++) {
case 0:
text = setSpanBetweenTokens(text, "$$", new StyleSpan(
Typeface.BOLD_ITALIC));
break;
case 1:
text = setSpanBetweenTokens(text, "##",
new ForegroundColorSpan(Color.RED));
break;
case 2:
text = setSpanBetweenTokens(text, "##",
new ForegroundColorSpan(Color.RED));
break;
case 3:
text = setSpanBetweenTokens(text, "##",
new ForegroundColorSpan(Color.RED));
break;
case 4:
break;
case 5:
text = setSpanBetweenTokens(text, "@@",
new ForegroundColorSpan(Color.BLUE));
break;
}
tV.setText(text);
}
}
/**
* Given either a Spannable String or a regular String and a token, apply
* the given CharacterStyle to the span between the tokens, and also remove
* tokens.
* <p>
* For example, {@code setSpanBetweenTokens("Hello ##world##!", "##",
* new ForegroundColorSpan(0xFFFF0000));} will return a CharSequence
* {@code "Hello world!"} with {@code world} in red.
*
* @param text
* The text, with the tokens, to adjust.
* @param token
* The token string; there should be at least two instances of
* token in text.
* @param cs
* The style to apply to the CharSequence. WARNING: You cannot
* send the same two instances of this parameter, otherwise the
* second call will remove the original span.
* @return A Spannable CharSequence with the new style applied.
*
* @see http
* ://developer.android.com/reference/android/text/style/CharacterStyle
* .html
*/
public static CharSequence setSpanBetweenTokens(CharSequence text,
String token, CharacterStyle... cs) {
// Start and end refer to the points where the span will apply
int tokenLen = token.length();
int start = text.toString().indexOf(token) + tokenLen;
int end = text.toString().indexOf(token, start);
if (start > -1 && end > -1) {
// Copy the spannable string to a mutable spannable string
SpannableStringBuilder ssb = new SpannableStringBuilder(text);
for (CharacterStyle c : cs)
ssb.setSpan(c, start, end, 0);
// Delete the tokens before and after the span
ssb.delete(end, end + tokenLen);
ssb.delete(start - tokenLen, start);
text = ssb;
}
return text;
}
}