Reputation:
I have written this code on render()
method. Now, I want to make the text blink, but it is not working
canvas.drawText(blinkText, 10, 10, paint);
if (blink == true) {
canvas.drawText(blinkText, 10, 10, paint);
} else {
canvas.drawText("Low Fuel", 10, 10, null);
}
and in update()
method
if (blink == false) {
blink = true;
} else {
blink = false;
}
Upvotes: 2
Views: 2148
Reputation: 70
if(System.currentTimeMillis() - blinkStart >= 150 && blink) {
blink = false;
lastUpdateTime = System.currentTimeMillis();
}
you can use thread for blink
Upvotes: 1
Reputation: 6834
If your update() method is called from a separate Thread repeatedly, it makes sense that you wouldn't see any changes because you're not only not invalidating the View, but could also be swapping the visibility too quickly to tell.
So first, let's declare a blink duration and a holder for our last update time: private static final int BLINK_DURATION = 350; // 350 ms private long lastUpdateTime = 0; private long blinkStart=0;
Now, assuming you're setting setting the Bitmap to be the src or background of the View (which you should be doing if you're animating on top of it), you should be able to draw the text over the View on its Canvas after the View's dispatchDraw(Canvas) call:
@Override
public void dispatchDraw(Canvas canvas) {
Paint paint = new Paint();
paint.setTextSize(40);
paint.setColor(Color.RED);
canvas.drawBitmap(back, width / 2 - back.getWidth() / 2, height / 2
- back.getHeight() / 2, null);
if (blink)
canvas.drawText(blinkText, back.getWidth() / 2,
back.getHeight() / 2, paint);
}
Note: generally you would use onDraw(Canvas), but in this situation the View could be a layout with a background and children, in which case we use dispatchDraw(Canvas) to make sure we actually draw above all the View's children.
Now that we have our drawing method setup, let's adjust your update method to only flip once the duration has passed, and then actually invalidate the View:
public void update() {
if (System.currentTimeMillis() - lastUpdateTime >= BLINK_DURATION
&& !blink) {
blink = true;
blinkStart = System.currentTimeMillis();
}
if (System.currentTimeMillis() - blinkStart >= 150 && blink) {
blink = false;
lastUpdateTime = System.currentTimeMillis();
}
}
Now it is working fine
Upvotes: 2