|
下面这段代码想要实现:主布局先加载layout1布局,5秒钟后在加载layout2布局。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RelativeLayout rlMain = (RelativeLayout)this.findViewById(R.id.rlMain);
LinearLayout l1 = (LinearLayout)this.getLayoutInflater().inflate(R.layout.layout1, null);
rlMain.addView(l1);
long currentTime = System.currentTimeMillis();
while(System.currentTimeMillis() - currentTime < 5000){
}
LinearLayout l2 = (LinearLayout)this.getLayoutInflater().inflate(R.layout.layout2, null);
rlMain.removeAllViews();
rlMain.addView(l2);
}
|
|
| 10分 |
你这是主线程这样写显然不行。
这样试试
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
LinearLayout l2 = (LinearLayout)this.getLayoutInflater().inflate(R.layout.layout2, null);
rlMain.removeAllViews();
rlMain.addView(l2);
}
}, 5000);
|
|
你这个while里永远不会执行的可好。
你可以用handler,delay5秒。 |
|
|
请问这样做的道理是什么啊?handler里的代码是另开了一个线程吗?应该没有吧,可是这样做为什么可以?
|
|
| 5分 |
也是运行在主线程里的,因为这个handler是在主线程创建的。你看下handler的构造函数就明白了 |
| 5分 |
1楼正解,用Handler发布消息,Handler是主线程的一个消息队列”管理员“,Handler()中postDelayed方法就可以实现你要的结果,他有两个参数,第一个是Runnable,第二个是Time,这个Time是以毫秒计数的。要想深入了解Handler多去搜搜吧,或者去看源码。
|
|
其实,你布局可以用viewstub代替
|
|