簡體   English   中英

android每5秒更改一次背景圖片

[英]android change background image every 5 seconds

我有圖像數組,我想用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.計時器具有第三個參數-間隔。 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]);
                        }
                    });
              }
        }
}

PS我不檢查代碼。 也許有一些錯誤

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM