2013-07-16 53 views
2

我正在尋找一種方法來從線程中調用invalidate方法。基本上我想要做的就是從DrawThread調用onDraw方法。從線程中調用invalidate方法

protected void onDraw(Canvas canvas) { 
    // Drawing commands go here 

    canvas.drawArc(oval, strt, arc, true, cPaint); 
    while(i<90) 
    { 
    canvas.drawText(z,300,300, tPaint); 

    break; 
    } 

class DrawThread extends Thread 
{ 
GameView a; 
Canvas canvas; 
DrawThread(GameView a) 
{ 
    this.a=a; 
    start(); 
} 

public void run() 
{ 
    a.flag2=true; 
    while(a.flag2) 
    { 
     try 
     { 
      sleep(200); 
     } 
     catch(Exception e) 
     { 
     } 

    if(!a.flag1) 
    { 
     a.x+=10; 

     if(!a.flag3) 
     { 
      a.strt-=15; 
      a.arc+=15; 
     } 
     else 
     { 
      a.strt+=15; 
      a.arc-=15; 
     } 

    } 

    if(a.flag1) 
    { 
     a.x-=10; 
     if(!a.flag3) 
      a.arc+=15; 
     if(a.flag3) 
      a.arc-=15; 
    } 

    if(a.x==600) 
    { 
     a.y+=60; 
     a.flag1=true; 
     a.strt=180; 
     a.arc=315; 
    } 

    if(a.x==30) 
    { 
     a.y+=60; 
     a.flag1=false; 
     a.strt=45; 
     a.arc=315; 

    } 
    if(a.y>=600) 
    { 
     a.y=60; 
    } 

    if(a.strt==0 || a.arc==360) 
    { 
     a.flag3=true; 
    } 

    if(a.strt==45 || a.arc==315) 
    { 
     a.flag3=false; 
    } 
    if(a.n1==a.x&&a.n2==a.y) 
    { 
     a.i+=1; 
     a.n1 = Math.random()*10; 
     a.n2 = Math.random()*60; 
    } 
    a.invalidate(); 
    } 
} 
} 

回答

2

使用postInvalidate()刷新非UI用戶線程的視圖。

public void invalidate()

在API級別1

無效整個視圖。如果視圖可見,onDraw(android.graphics.Canvas)將在未來的某個時間點被調用。 這必須從UI線程中調用。要從非UI線程調用,請調用postInvalidate()。

public void postInvalidate()

在API級別1

導致一個無效發生通過事件循環隨後的循環。 使用它可以使非UI線程的視圖無效。

只有在將此視圖連接到窗口時,才能從UI線程之外調用此方法。

更多信息@

http://developer.android.com/reference/android/view/View.html

+0

先生我如何附上了一個窗口我的觀點? – user2586942

+0

查看窗口?你可以使用'setContentView(myview)MyView myview = new MyView();'MyView是一個類,然後是外觀'View'。 – Raghunandan

+0

和先生,如果我想添加一個按鈕到這個view.how你建議我做那個。我是一個完整的初學者在android。 – user2586942

相關問題