我想每秒更改繪製的矩形的顏色。我有下面的代碼來做到這一點。自定義視圖忽略延遲
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