android每隔5秒更改一次背景图片

时间:2014-07-23 16:31:45

标签: java android android-imageview

我有图像数组,我想用rundom每隔5秒更改一次背景图像。 我写了一些代码,但我有android.view.ViewRootImpl $ CalledFromWrongThreadException: 只有创建视图层次结构的原始线程才能触及其视图Exeption。什么是这个问题的解决方案。

public class StradaContact extends Fragment {

private int[] image_rundow = {

R.drawable.slideone, R.drawable.slidetwo, R.drawable.slidetree

};

private ImageView mapimg;
Reminder claass;

public StradaContact() {

}

public static StradaContact newInstance() {
    return new StradaContact();
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.strada_contact, container,
            false);

    claass = new Reminder(5);

    return rootView;
}

public class Reminder {

    Timer timer;

    public Reminder(int seconds) {
        timer = new Timer();
        timer.schedule(new RemindTask(), seconds * 1000);
    }

    class RemindTask extends TimerTask {
        public void run() {
            while (true) {
                Random rand = new Random();

                int index = rand.nextInt(image_rundow.length);

                mapimg.setBackgroundResource(image_rundow[index]);

                timer.cancel();
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }

            // Terminate the timer thread
        }
    }
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

}

}

1 个答案:

答案 0 :(得分:0)

我改进了你的课程: 1.定时器有第三个参数 - 间隔。 2. UI线程的UI代码(它是关于mapimg.setBackgroundResource(...)) 如何取消你知道的任务。你可以在没有帮助的情况下做到这一点。

public class Reminder {
        Timer timer;
        public Reminder(int seconds) {
            timer = new Timer();
            timer.schedule(new RemindTask(), seconds * 1000,5000);
        }

        class RemindTask extends TimerTask {
            public void run() {
              getActivity().runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            Random rand = new Random();
                            int index = rand.nextInt(image_rundow.length);
                            mapimg.setBackgroundResource(image_rundow[index]);
                        }
                    });
              }
        }
}

P.S 我不检查代码。也许它有一些错误

相关问题