我想制作一个会改变我活动布局的线程......我有2个布局:welcomepage和activity_main ... 线程的目标:当我启动我的应用程序时,欢迎页面布局将在5秒内显示,之后布局将再次为activity_main ...
我编写了如下代码:
package com.example.tripolimazad;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
public TextView counter = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcomepage);
counter = (TextView) findViewById(R.id.Counter);
Thread th=new Thread(){
@Override
public void run(){
try
{
Thread.sleep(10000);
setContentView(R.layout.activity_main);
}catch (InterruptedException e) {
}
}
};
th.start();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
但它不起作用!有任何解决方案PLZ!
答案 0 :(得分:2)
您无法在非UI线程上更改UI,但在Activity
中,您可以使用runOnUiThread
方法:
runOnUiThread(new Runnable() {
@Override
public void run() {
setContentView(R.layout.activity_main);
}
});
这似乎很奇怪,在你的onCreate
中有这个。
答案 1 :(得分:1)
您也可以尝试使用CountDownTimer之类的内容:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcomepage);
//display the logo during 5 secondes,
new CountDownTimer(5000,1000){
@Override
public void onTick(long millisUntilFinished){}
@Override
public void onFinish(){
//set the new Content of your activity
MainActivity.this.setContentView(R.layout.main);
}
}.start();
//...
}
有关详情,请参阅Displaying logo for few seconds at application start。
答案 2 :(得分:0)
UI相关操作必须仅在UI线程上完成,并且不能像在您那样在非UI线程中完成。但您可以按如下方式从非UI线程更新UI:
activityContext.runOnUiThread(new Runnable() {
@Override
public void run() {
setContentView(R.layout.activity_main);
}
});
但是,对于您提到的情况,更好的方法是使用Android提供的异步任务。您可以尝试以下操作:
/*
* Activity/Thread to display the **welcomepage**
* when the app is started.
*/
public class SplashActivity extends Activity {
// how long until we go to the next activity
protected int _splashTime = 5000; // 5 seconds
// thread to display welcome page
private Thread splashTread;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_welcome_page_layout);
// thread for displaying the WelcomeScreen
splashTread = new Thread() {
@Override
public void run() {
try {
synchronized (this) {
// wait 5 sec
wait(_splashTime);
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
// finish the current splashactivity
finish();
// start MainActivity as next activity
startActivity(new Intent(SplashActivity.this, MainActivity.class));
}
}
};
// start the thread.
splashTread.start();
}
}
答案 3 :(得分:0)
或者,您可以使用处理程序来避免创建新线程,如下所示:
getWindow().getDecorView().getHandler().postDelayed(new Runnable() {
@Override public void run() {
setContentView(R.layout.activity_main);
}
}, 10000);