开发者

How I can use a handler to change the ImageView's picture after 2 sec, and 5?

开发者 https://www.devze.com 2023-03-18 11:08 出处:网络
I have an ImageView, what shows one picture . I tried to use a thread, but it doesn\'t change the picture. Then I tried a handler, but it doesn\'t treat the sleep(int) method, so I can\'t increase the

I have an ImageView, what shows one picture . I tried to use a thread, but it doesn't change the picture. Then I tried a handler, but it doesn't treat the sleep(int) method, so I can't increase the time, what elapsed. How can I make it? Can you write an example please?

Here is my original code:

@Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
                Thread timer = new Thread() {
                    public void run() {
                        int time = 0;
                        while (time <= 7000) {
                            try {
                                sleep(100);
                                time =+ 100;
                                if(time == 2000) {
                                    radar.setImageResource(R.drawable.radar_full);
                                }
                                if(time == 5000) {
                                    radar.setImageResource(R.drawable.radar_50);
                                }
                                if(tim开发者_StackOverflowe == 7000) {
                                    radar.setImageResource(R.drawable.radar_found);
                                }
                            } catch (InterruptedException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();


        }
};
                    timer.start();
                    };
                };


Here are a couple of tutorials for you:

Android GUI thread timer sample

A Stitch in Time

It appears that you need to learn more about Threads and Handlers in general. However, it's worth pointing out that you cannot update a UI element from within a Thread, which is what I'm guessing you tried to do; UI updating (such as changing the content of an ImageView) must be done within the UI thread. Therefore, updating the image inside a Handler on the UI thread was going in the right direction. You just need a way to call that Handler at timed intervals, and the tutorial above demonstrates one such way, by simply posting messages to the Handler.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号