2011-02-05 129 views
0

我有點沮喪,因爲如何做到這一點..任何人都可以請幫助我或指引我在正確的方向?,與下面的代碼。我只需要在2秒的時間間隔內改變顏色圈數,並且我無法找到任何東西。基本上,如果我能理解以下情況,就足夠了Android改變線程顏色

1.我有一個類調用DrawCircle,Exatends View 2.我有實例化DrawCircle類的Activity程序。 問題:

1 - 我在哪裏創建線程?在Activity中還是在DrawCircle類中?如果我這樣做,我應該在run()中放什麼?

2 - 我會在哪裏放置「Thread.sleep(2000)」? 3.最後,我需要確保我在DrawCircle類中有什麼,以及我應該確保在Activity或主程序中有什麼?

我只需要做出一個圓改變顏色以2秒

間隔

非常感謝你的所有(我已經花了12小時了努力使這項工作的幫助,也許我不應該這樣做了)

下面是代碼

public class ColorChanges extends Activity { 
    DrawCircle dc; 
    Paint pa = new Paint(); 


    @Override 
    public void onCreate(Bundle savedInstanceState) 
    {  
     super.onCreate(savedInstanceState); 

       //this line does not work 

      dc = new DrawCircle(this,pa); 
      dc.setBackgroundColor(Color.WHITE);  
      drawCircleToCanvas(); 
      setContentView(dc);  
      } 

    void drawCircleToCanvas() 
    {  

     final Handler handler = new Handler() 
      {     
      public void handleMessage(Message msg) { 
       pa.setColor(Color.BLUE); 
       dc.setBackgroundColor(Color.RED); 

       dc.postInvalidate();       
       }     
      };   
      Thread updateUI = new Thread()  
      {       
       public void run() {        

        try { 
         for (int i=0;i<20;i++){ 
         Thread.sleep(2000); 
         handler.sendMessage(handler.obtainMessage()); 
         } 
        } catch (InterruptedException e) { 
         // TODO Auto-generated catch block 
         e.printStackTrace(); 
        } 

       }      
       };      
       updateUI.start();  

       } 

}

這是活動,這裏是我的

0級
public class DrawCircle extends View { 
Paint p1 = new Paint(); 
Paint p2 = new Paint(); 
Paint p3 = new Paint(); 

Paint pAll[] = new Paint[3]; 


public DrawCircle(Context context, AttributeSet attrs) { 
    super(context, attrs); 
    // TODO Auto-generated constructor stub 
} 
public DrawCircle(Context context, AttributeSet attrs, int defStyle) { 
    super(context, attrs, defStyle); 
    // TODO Auto-generated constructor stub 
} 

public DrawCircle(Context context, Paint p) { 
    super(context); 
     p1 = p; 
     p1.setStyle(Paint.Style.STROKE); 
     p1.setColor(Color.GREEN); 
     p1.setStyle(Paint.Style.FILL); 



    // TODO Auto-generated constructor stub 
} 

@Override 
public void onDraw(Canvas canvas) 
{  

      canvas.drawCircle(200, 200, 100, p1); 
} 

}

+1

你能發佈你的實際代碼嗎?我不清楚你是如何或爲什麼要在單獨的(關閉UI)線程中執行此操作。 – 2011-02-05 21:43:03

+0

如果我把它放在相同的用戶界面,我做Thread.sleep(2000),它會出來所有黑色 – earm 2011-02-05 22:22:39

回答

0

做它在UI線程。而不是Thread.sleep,使用Handler.postDelayed(),延遲時間爲2秒。