2012-02-10 60 views
0

我正在android中的ProgressBar類上工作,但我無法通過5秒的時間使它進展並加載應用程序。一切正常,但進度條沒有進展。這是代碼。Android ProgressBar與線程

public class StartPoint extends Activity{ 

ProgressBar progressBar; 
private int progressBarStatus = 0; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.splash); 

    progressBar = (ProgressBar)findViewById(R.id.progressBar1); 


    Thread timer = new Thread(){ 
     public void run(){ 
      try{ 
       sleep(5000); 
       while(progressBarStatus < 5000){ 
        progressBar.setProgress(progressBarStatus); 
        progressBarStatus += 1000; 

       } 
      }catch(InterruptedException e){ 
       e.printStackTrace(); 
      }finally{ 
       Intent openMainList = new Intent(StartPoint.this, in.isuru.caf.MainList.class); 
       startActivity(openMainList); 
      } 
     } 
    }; 
    timer.start(); 
} 

protected void onPause(){ 
    super.onPause(); 
    finish(); 
} 

} 

這裏是佈局文件splash.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:orientation="vertical" > 

<ImageView 
    android:id="@+id/imageView1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:src="@drawable/mary_mother_of_god" /> 

<ProgressBar 
    android:id="@+id/progressBar1" 
    style="?android:attr/progressBarStyleHorizontal" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_weight="1.67" /> 

</LinearLayout> 

回答

9

無法從不同的線程更新UI控件。你需要做的事情如下:

Thread timer = new Thread(){ 
    public void run(){ 
     try{ 
      sleep(5000); 
      while(progressBarStatus < 5000){ 
       StartPoint.this.runOnUIThread(new Runnable(){ 
        public void run() 
        { 
         progressBar.setProgress(progressBarStatus); 
         progressBarStatus += 1000; 
        } 
       }); 

      } 
     }catch(InterruptedException e){ 
      e.printStackTrace(); 
     }finally{ 
      Intent openMainList = new Intent(StartPoint.this, in.isuru.caf.MainList.class); 
      startActivity(openMainList); 
     } 
    } 
}; 
timer.start(); 
+0

我不明白。你可以更具體或發佈整個代碼。告訴我,當我睡5000毫秒,我可以開始上面的方法或我需要聲明分開。 – Isuru 2012-02-10 19:44:27

+0

我編輯了上面的代碼。 – CaseyB 2012-02-10 20:21:24

+0

謝謝你的工作! – Isuru 2012-02-10 20:45:57