为什么活动不会在Framelayout中显示Sexdom对象的第一个视图,但它会等待10秒并仅显示MainWindow。在framelayout中?
private FrameLayout frameLayout = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
frameLayout = new FrameLayout(getApplicationContext());
setContentView(frameLayout);
SexDom sexDom = new SexDom(getApplicationContext());
MainWindow mainWindow = new MainWindow(getApplicationContext());
frameLayout.addView(sexDom.getView());
SystemClock.sleep(10000);
frameLayout.removeAllViews();
frameLayout.addView(mainWindow.getView());
}
答案 0 :(得分:0)
这里要澄清的第一件事是activity lifecycle.我们在这里可以发现onCreate
有创建活动视图的任务,但在调用onStart
之前不会显示活动。从这里开始,我们可以推断出一个长时间处理任务(如SystemClock.sleep(10000)
)会使系统保持忙碌状态(这可以推广到MainThread
上运行的任何方法),因为它将延迟活动的创建,显示白屏(直到长任务完成),而不是实际的内容视图。
基本上,你想要这样的东西:
1. The activity is created and displayed
2. Add the first view
3. Wait for 10 seconds
4. First view is removed
5. And then add the second view
但结果却是这样的:
1. The activity is created
2. Add the first view
3. Wait for 10 seconds
4. Remove first view
5. Add the second view
6. Activity is finished creating
7. Activity is displayed with second view by default
这里的关键是让MainThread
继续创建活动而不与之交互。如果您仍希望在给定延迟后在这些视图之间切换,则可以使用Handler
。
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
frameLayout.removeAllViews();
frameLayout.addView(mainWindow);
}
}, 10000);