问题
I want to use the setContentView() method after a thread has completed his task. But how could I realize this, as its not possible to use this method inside the thread? When using this method in the onCreate() method while the thread is running, I also don´t get the correct result, cause the layout wich should be displayed with the first "setContentView(R.layout.load_screen)" is not displayed.
My onCreate() Method:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Open loading screen
setContentView(R.layout.load_screen);
this.loadingScreen(); // In this method the new Thread will start.
}
My loadingScreen() Method: (After the thread completed I would like to use setContentView() again)
public void loadingScreen(){
// prepare for a progress bar dialog
progressBar = new ProgressBar(this);
progressBar = (ProgressBar)findViewById(R.id.progressBar1);
//reset progress bar status
progressBarStatus = 0;
new Thread(new Runnable() {
public void run() {
while (progressBarStatus < 100) {
try {
Thread.sleep(100);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// process some tasks
progressBarStatus = doSomeTasks();
// your computer is too fast, sleep 1 second
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Update the progress bar
progressBarHandler.post(new Runnable() {
public void run() {
progressBar.setProgress(progressBarStatus);
}
});
}
// ok, file is downloaded,
if (progressBarStatus >= 100) {
// sleep 2 seconds, so that you can see the 100%
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
回答1:
you can use Handler to update the ui inside the thread. or u can simply use runOnUiThread to update the ui. and u dont want to use setcontentview method to change the ui, u can simply use layout inflater to fetch another layout to ur viewgroup.
来源:https://stackoverflow.com/questions/22656915/android-use-setcontentview-after-thread-finished