2013-09-23 30 views
0

這裏陸續加載的TextView一個是我的onCreate方法如何使用線程

 @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); 
     // Show the splash screen 
     setContentView(R.layout.progressbar); 
     initActionbar(); 




     mytext=(TextView)findViewById(R.id.progresstextview1); 
     mytext1 = (TextView)findViewById(R.id.progresstextview2); 
     mytext2 = (TextView)findViewById(R.id.progresstextview3); 



     Thread t = new Thread(); 
     Thread t1 = new Thread(); 
     Thread t2 = new Thread(); 

     t.start(); 
     mytext.setVisibility(View.VISIBLE); 


     t1.start(); 
     mytext1.setVisibility(View.VISIBLE); 


     t2.start(); 
     mytext2.setVisibility(View.VISIBLE); 
    } 

這裏是我的run方法

@Override 
    public void run() { 
     // TODO Auto-generated method stub 
     for(int i=0;i<1000;i++) 
     { 

     } 
    } 

我希望我的3 TextView中陸續有一些延遲加載一個問題是所有的三個textview獲得非常先加載和延遲不會發生。另一個問題是主UI線程幾秒後啓動。任何幫助,在這方面將非常感謝!

+0

使用處理程序或定時器,您無法從線程更新ui。你將需要使用'runOnUiThread'。 – Raghunandan

+0

可以發佈定時器解決方案嗎? – Chiradeep

+0

http://stackoverflow.com/questions/17839419/android-thread-for-a-timer/17839725#17839725。檢查此倒計時處理程序和timertask – Raghunandan

回答

1

偉大的方式做這樣的事情是使用android.os.Handler

見例如:

 mytext=(TextView)findViewById(R.id.progresstextview1); 
     mytext1 = (TextView)findViewById(R.id.progresstextview2); 
     mytext2 = (TextView)findViewById(R.id.progresstextview3); 

     uiThreadHandler = new Handler();  
     showDelayed(mytext, 1000); 
     showDelayed(mytex1, 2000); 
     showDelayed(mytex2, 3000); 
    } 

    public void showDelayed(final View v, int delay){ 
     uiThreadHandler.postDelayed(new Runnable() { 
      @Override 
      public void run() { 
       v.setVisibility(View.Visible); 
      } 
     }, delay); 
    } 

而且,要記住:創建線程可能是一個昂貴的操作,所以儘量避免行代碼是這樣

new Thread().start(); 

相反 - 嘗試用另一種方法,或者至少使用線程池從執行程序的框架

+0

感謝您的答案..它工作很酷..我會記住你的話 – Chiradeep