2013-01-12 18 views
0

我試圖創建一個倒計時器並將其顯示在畫布上。這是我如何顯示它。SurfaceDown中的CountDownTimer

public class DrawView extends SurfaceView { 
private Paint textPaint = new Paint(); 
Bitmap GameBg; 
DisplayMetrics metrics; 
int screenWidth = 0; 
int screenHeight = 0; 
Rect dest; 
Paint paint; 
String timer; 
public DrawView(Context context) { 
    super(context); 
    // Create out paint to use for drawing 
    textPaint.setARGB(255, 200, 0, 0); 
    textPaint.setTextSize(60); 
    // This call is necessary, or else the 
    // draw method will not be called. 
    setWillNotDraw(false); 

    GameBg = BitmapFactory.decodeResource(getResources(),R.drawable.gembackground); 
    metrics = context.getResources().getDisplayMetrics(); 
    screenWidth = metrics.widthPixels; 
    screenHeight = metrics.heightPixels; 
    dest = new Rect(0, 0, screenWidth, screenHeight); 
    paint = new Paint(); 
    paint.setFilterBitmap(true); 

    new CountDownTimer(60000, 1000) { 

     public void onTick(long millisUntilFinished) { 
      timer = String.valueOf(millisUntilFinished/1000); 
     } 

     public void onFinish() { 
     } 
     }.start(); 

    } 

    @Override 
    protected void onDraw(Canvas canvas){ 
    // A Simple Text Render to test the display 
    canvas.drawBitmap(GameBg, null, dest, paint); 
    canvas.drawText(timer, screenWidth - 50, screenHeight - 50, paint); 

    } 

}

我可以顯示計時器,但它並不倒計時。有任何想法嗎?

回答

1

你永遠不會對timer中的新值做任何事情。嘗試這樣的:

new CountDownTimer(60000, 1000) { 
    public void onTick(long millisUntilFinished) { 
     timer = String.valueOf(millisUntilFinished/1000); 
     invalidate(); // Force the View to redraw 
    } 

    public void onFinish() {} 
}.start(); 
+0

那麼做到了。所以我應該總是放棄並使其無效以使視圖重新繪製? – ljpv14

+0

您應該嘗試使可能的最小區域失效。考慮使用這個['invalidate()'](http://developer.android.com/reference/android/view/View.html#invalidate%28int,%20int,%20int,%20int%29)與適當的座標。 – Sam