简体   繁体   English

如何使setContentView()与线程一起正常工作?

[英]How to make setContentView() work properly with a thread?

I have 2 layouts, and 2 activities, each one corresponding to a layout, one of them is SplashActivity, and the other is MainActivity. 我有2个布局和2个活动,每个活动对应一个布局,其中一个是SplashActivity,另一个是MainActivity。 I want the application to open the splashActivity(splash XML shows the logo), wait for 5 seconds and open the main activity, but because of the thread, the setContentView doesn't work properly. 我希望应用程序打开splashActivity(splash XML显示徽标),等待5秒钟并打开main活动,但是由于线程的原因,setContentView无法正常工作。

PS Also any relative documentation links would be very useful, thanks in advance PS此外,任何相关的文档链接将非常有用,在此先感谢

@Override @覆盖

protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); 受保护的void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState); setContentView(R.layout.splash_screen); 的setContentView(R.layout.splash_screen);

  Thread timer = new Thread() { public void run() { try { sleep(5000); } catch (InterruptedException ex) { ex.printStackTrace(); } try { Class mainMenu = Class.forName("com.carmine.project.MenuActivity"); Intent openMainMenu = new Intent(SplashActivity.this, mainMenu); startActivity(openMainMenu); } catch (ClassNotFoundException e) { e.printStackTrace(); } } }; timer.run(); } 

your problem is that you are calling timer.run(); 您的问题是您正在调用timer.run(); instead of timer.start(); 而不是timer.start();

timer.run(); calls the run method on the same context of the thread that executed that line (making the UI Thread, in your case, wait for 5s, and blocking every other operation). 在执行该行的线程的同一上下文中调用run方法(在您的情况下,使UI线程等待5s,并阻塞其他所有操作)。 timer.start() spawns a new thread timer.start()产生一个新线程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM