【问题标题】:android change background image every 5 secondsandroid每5秒改变一次背景图片
【发布时间】:2014-07-23 16:31:44
【问题描述】:

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

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);

}

}

【问题讨论】:

  • 正如异常所说,只有创建视图的线程才能更改其属性。查看 AysncTask 或 View.PostDelayed
  • Threading UI updates in Android 的可能重复项

标签: java android android-imageview


【解决方案1】:

我改进了你的课程: 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]);
                        }
                    });
              }
        }
}

附言 我不检查代码。也许它有一些错误

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-31
    • 2021-03-16
    • 1970-01-01
    • 2014-10-12
    • 1970-01-01
    • 2013-06-19
    相关资源
    最近更新 更多