我想每秒更改绘制的矩形的颜色。我有下面的代码来做到这一点。自定义视图忽略延迟
private Runnable mRunnable;
private int mIndex;
...
public BlinkingView(Context context) {
this(context, null);
mRunnable = new Runnable() {
@Override
public void run() {
long currentMillis = System.currentTimeMillis();
Log.d("Tag", "Millis Dif -- " + (mIndex== 0 ? "GREEN" : "RED") + " :: " + (currentMillis - lastMillis));
lastMillis = currentMillis;
// Set the paint color to be drawn.
mColoredRectPaint.setColor(mIndex++ % 2 == 1 ? Color.RED : Color.GREEN);
// Update the view.
invalidate();
// Run again.
postDelayed(mRunnable, 1000);
}
};
post(mRunnable);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Draw the colored rectangle
canvas.drawRect(mLeft, mTop, mRight, mBottom, mColoredRectPaint);
// Draw a boarder rectangle.
canvas.drawRect(mStrokeLeft, mStrokeTop, mStrokeRight, mStrokeBottom, mOuterRectPaint);
}
但是,只有每隔调用postDelayed
被延迟。我注销每次调用runnable的run方法之间的毫秒数。
D/Tag: DURATION -- GREEN :: 1000
D/Tag: DURATION -- RED :: 1
D/Tag: DURATION -- GREEN :: 1002
D/Tag: DURATION -- RED :: 3
D/Tag: DURATION -- GREEN :: 1001
D/Tag: DURATION -- RED :: 3
D/Tag: DURATION -- GREEN :: 1001
D/Tag: DURATION -- RED :: 2
所以每隔呼叫被推迟。任何想法为什么?
延迟通常会有误差范围,如果我没有记错 – JoxTraex
我认为这保证这将是该时间之后,但不一定正是时候。而且,整整一秒也是一个相当大的误差。 –
你应该澄清的一件事是你所指的日志。并显示代码完全是你写的。 – JoxTraex