Sleep function in android program

落花浮王杯 提交于 2019-11-30 17:43:13

Well, if you want the UI to remain responsive you can't block the UI thread with Thread.sleep there.

Create a new thread, then sleep it. After the sleep, run the method for changing the view drawable on the UI thread

new Thread(new Runnable() {
    @Override
    public void run() {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                pic.get(0).setImageDrawable(getResources().getDrawable(R.drawable.coin));
            }
        });
    }
}).start();

Create an image array and set a handler. Using postDelayed doesn't block the thread.

            int[] imageArray = { R.drawable.img_1, R.drawable.img_2,
            R.drawable.img_3, R.drawable.img_4,
            R.drawable.img_5};

            Handler handler = new Handler();
            Runnable runnable = new Runnable() {
                int i = 0;

                public void run() {
                    imageView1.setImageResource(imageArray[i]);
                    i++;
                    if (i > imageArray.length - 1) {
                        i = 0;
                    }
                    handler.postDelayed(this, 5000); //displays every 5 seconds
                }
            };
            handler.postDelayed(runnable, 5000);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!