Vladimir Vladimir - 3 months ago 24
Android Question

android blink character in textview

Can I set a single character inside a TextView to blink?

Using "spannable" I can set colors, font-weight etc. but I did not found anything about blink.

"Animation" AFAIK works on the whole view.

Suggestions anyone?

Answer

you can start playing with that custom class:

class FCS extends ForegroundColorSpan implements TimeAnimator.TimeListener {

    private TextView tv;
    private int[] colors;
    private int color;
    TimeAnimator animator;
    ArgbEvaluator evaluator;

    public FCS(TextView tv, int[] colors) {
        super(colors[0]);
        this.tv = tv;
        this.colors = colors;
        animator = new TimeAnimator();
        animator.setTimeListener(this);
        evaluator = new ArgbEvaluator();
        animator.start();
    }

    @Override
    public void updateDrawState(TextPaint ds) {
        ds.setColor(color);
    }

    @Override
    public void onTimeUpdate(TimeAnimator animation, long totalTime, long deltaTime) {
        float sin = (float) (Math.sin(Math.PI * totalTime / 1000f));
        float fraction = sin * sin;
//        float fraction = (float) (-Math.cos(2*Math.PI * totalTime / 1000f) + 1) / 2f;
        color = (int) evaluator.evaluate(fraction, colors[0], colors[1]);
        tv.invalidate();
        if (totalTime > 20000) {
            animator.end();
        }
    }
}

test code (place it inside Activity#onCreatemethod):

TextView tv = new TextView(this);
tv.setTextSize(40);
int[] colors = {
        tv.getCurrentTextColor(),
        Color.RED,
};
SpannableStringBuilder ssb = new SpannableStringBuilder();
ssb.append("Poeta de ");
int start = ssb.length();
ssb.append("magnum stella, dignus sectam!");
ssb.setSpan(new FCS(tv, colors), start, start+1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
tv.setText(ssb);
setContentView(tv);
Comments