如何使的setContentView()与线程正常工作? [英] How to make setContentView() work properly with a thread?

查看:120
本文介绍了如何使的setContentView()与线程正常工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2的布局,和2的活动,每一个对应于一个布局,其中之一是SplashActivity,而另一个是MainActivity。我希望应用程序打开splashActivity(闪XML显示标志),等待5秒钟,打开主要活动,但由于螺纹的的setContentView不能正常工作。

P.S。同时,任何相关的文档链接将是非常有用的,在此先感谢


  

@覆盖


  
  

保护无效的onCreate(捆绑savedInstanceState){
          super.onCreate(savedInstanceState);
          的setContentView(R.layout.splash_screen);

 发定时器=新的Thread(){
        公共无效的run(){
            尝试{
                睡眠(5000);
            }赶上(InterruptedException的前){
                ex.printStackTrace();
            }            尝试{
                类MAINMENU =的Class.forName(com.carmine.project.MenuActivity);
                意图openMainMenu =新意图(SplashActivity.this,MAINMENU);
                startActivity(openMainMenu);
            }赶上(ClassNotFoundException的E){
                e.printStackTrace();
            }
        }
    };    timer.run();
}



解决方案

你的问题是,你正在调用 timer.run(); 而不是 timer.start();

timer.run(); 呼吁所有执行该行(使UI线程,你的情况线程的同一背景下的run方法,等待5秒和阻塞所有其他操作)。 timer.start()生成一个新的线程

I have 2 layouts, and 2 activities, each one corresponding to a layout, one of them is SplashActivity, and the other is 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.

P.S. Also any relative documentation links would be very useful, thanks in advance

@Override

protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); 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(); instead of 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). timer.start() spawns a new thread

这篇关于如何使的setContentView()与线程正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆