简体   繁体   中英

Android change imageview image on interval

I simply want to change the bitmap image of an imageview on a set interval ( 2 seconds)

I have tried this but the app crashes:

private void prefromRadarInterval() {
    int delay = 1000; // delay for 0 sec.
    int period = 1000; // repeat every 1 seconds.
    timer = new Timer();
    timer.scheduleAtFixedRate(new SampleTimerTask(), delay, period);
}

public class SampleTimerTask extends TimerTask {
    @Override
    public void run() {
        //MAKE YOUR LOGIC TO SET IMAGE TO IMAGEVIEW
        imageview_radarcurrent.setImageBitmap(radar_animation[flag]);
        flag++;
        if(flag > 9) {
            flag = 0;
        }
    }
}

The log cat prints this:

01-12 04:51:51.688: E/AndroidRuntime(19688): android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

Help and explanation would be appreciated!

Your problem is that the UI can only be modified buy the UI thread, and your TimerTask is running on it's own thread. The easiest way to solve this is probably by posting through a handler to the UI thread.

Take a look at this thread: Android timer updating a textview (UI)

You should call the setImageBitmap() from the UI thread. For example:

activity.runOnUiThread(new Runnable() {

            @Override
            public void run() {
                // Write your code here
            }
});

... or post it with a Runnable:

imageview_radarcurrent.post(new Runnable() {

            @Override
            public void run() {

            }
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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