我想用计时器多次更改文本部分的颜色。
最简单的方法是这样的:
SpannableStringBuilder ssb = new SpannableStringBuilder(mainText);
ForegroundColorSpan span = new ForegroundColorSpan(Color.BLUE);
ssb.setSpan(span, start, end, 0);
tv.setText(ssb);
但是如果我在一秒钟内多次运行上面的代码,我实际上每次都会更改 TextView
的整个(大)文本,因此不需要的内存-CPU 负载会发生在低端设备。
如何在 TextView
上有一个 Span
并且只更改 Span
的开始和结束位置?
它会完全起作用还是会在幕后进行全文替换?
我的文本是固定的,永远不会改变。
最佳答案
跨度移动不调用setText
方法的解决方法:
final TextView tv = new TextView(this);
tv.setTextSize(32);
setContentView(tv);
SpannableStringBuilder ssb = new SpannableStringBuilder("0123456789012345678901234567890123456789");
ssb.append(ssb).append(ssb);
tv.setText(ssb, BufferType.SPANNABLE);
final Spannable sp = (Spannable) tv.getText();
final ForegroundColorSpan span = new ForegroundColorSpan(0xffff0000);
Runnable action = new Runnable() {
@Override
public void run() {
sp.setSpan(span, start, start + 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
start++;
if (start <= sp.length() - 4) {
tv.postDelayed(this, 50);
}
}
};
tv.postDelayed(action, 1000);
动态变色解决方案:
class HSVSpan extends CharacterStyle {
int color;
float[] hsv = {0, 1, 1};
@Override
public void updateDrawState(TextPaint tp) {
tp.setColor(color);
}
public void update() {
hsv[0] += 5;
hsv[0] %= 360;
color = Color.HSVToColor(hsv);
// Log.d(TAG, "update " + Integer.toHexString(color));
}
}
和测试代码:
final TextView tv = new TextView(this);
setContentView(tv);
SpannableStringBuilder ssb = new SpannableStringBuilder("0123456789");
final HSVSpan span = new HSVSpan();
ssb.setSpan(span, 2, 6, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
tv.setText(ssb);
tv.setTextSize(32);
Runnable action = new Runnable() {
@Override
public void run() {
span.update();
tv.invalidate();
tv.postDelayed(this, 50);
}
};
action.run();
关于android - TextView 中动态文本颜色更改的最有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21496140/