TextView中动态文本颜色更改的最有效方法 [英] Most efficient way for Dynamic Text Color Change in TextView

查看:18
本文介绍了TextView中动态文本颜色更改的最有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用计时器多次更改文本部分的颜色.

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);

但是,如果我在一秒钟内多次运行上述代码,我实际上每次都会更改 TextView 的整个(大)文本,因此会在低端专门发生不需要的内存-CPU 负载设备.

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.

我怎样才能在 TextView 上有一个 Span 并且只更改 Span 的开始和结束位置?

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.

推荐答案

不调用setText方法的span移动解决方案:

Solution for span movement without calling setText method:

    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();

这篇关于TextView中动态文本颜色更改的最有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆