关于动态加载布局显示的问题

Android 码拜 9年前 (2015-05-10) 789次浏览 0个评论

下面这段代码想要实现:主布局先加载layout1布局,5秒钟后在加载layout2布局
但实际情况是:系统过了5秒后直接显示layout2布局,可见用addView加载完布局后系统并不立刻刷新屏幕。
那系统是什么时刻刷新屏幕呢?如果我想实现目标应该怎样写代码?

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分
引用 3 楼 dghjkoll 的回复:

请问这样做的道理是什么啊?handler里的代码是另开了一个线程吗?应该没有吧,可是这样做为什么可以?

也是运行在主线程里的,因为这个handler是在主线程创建的。你看下handler的构造函数就明白了

5分
1楼正解,用Handler发布消息,Handler是主线程的一个消息队列”管理员“,Handler()中postDelayed方法就可以实现你要的结果,他有两个参数,第一个是Runnable,第二个是Time,这个Time是以毫秒计数的。要想深入了解Handler多去搜搜吧,或者去看源码。
其实,你布局可以用viewstub代替

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明关于动态加载布局显示的问题
喜欢 (0)
[1034331897@qq.com]
分享 (0)

文章评论已关闭!