5

I want to change color of parts of a text several times with a timer.

Simplest way is this:

SpannableStringBuilder ssb = new SpannableStringBuilder(mainText);
ForegroundColorSpan span = new ForegroundColorSpan(Color.BLUE);
ssb.setSpan(span, start, end, 0);
tv.setText(ssb);

But if I run the above code several times in a second, I actually change the whole (large) text of TextView each time so a unwanted memory-CPU load will happen specifically on lower-end devices.

How can I have a single Span on TextView and only change the Span start and end position?

Will it work at all or a full text replace will happen behind the scene?

My text is fixed and won't change never.

4

3 回答 3

8

不调用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();
于 2014-02-01T09:38:31.567 回答
1

执行以下代码一次:

SpannableStringBuilder ssb = new SpannableStringBuilder(mainText);
ForegroundColorSpan span = new ForegroundColorSpan(Color.BLUE);

每次您想更改跨度时,请执行以下操作:

ssb.clearSpans()
ssb.setSpan(span, start, end, 0);
tv.setText(ssb);
于 2014-02-01T09:21:56.060 回答
0

今天下午我遇到了同样的问题,这是我的解决方案:

tv.setText(yourText, TextView.BufferType.SPANNABLE);
ForegroundColorSpan span = new ForegroundColorSpan(Color.BLUE);
((Spannable) article.getText()).setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

我发现这是一种更有效的方法,在我的项目中,我使用 set-whole-text 方法花费了 400~600 毫秒,这种方式只有 0 或 1 毫秒。

于 2015-12-24T08:57:20.413 回答