how to continuously switch textswitcher between two values every 2 seconds

有些话、适合烂在心里 提交于 2019-12-04 09:32:20

try using timer:

Timer timer = new Timer("desired_name");
timer.scheduleAtFixedRate(
    new TimerTask() {
        public void run() {
            //switch your text using either runOnUiThread() or sending alarm and receiving it in your gui thread
        }
    }, 0, 2000);

Reference for runOnUiThread. You cannot update gui elements from non-ui threads, so trying to update it from doInBackground() method of AsyncTask will lead to error.

An alternative easier method of achieving this is to use a viewFlipper rather than a viewSwitcher. This allows you to do everything that you want using the XML layout alone:

<ViewFlipper
    android:id="@+id/viewFlipper1"
    android:autoStart="true"
    android:flipInterval="3000">
        <TextView
            android:id="@+id/on_textview"
            android:text="ON" />
        <TextView
            android:id="@+id/off_textview"
            android:text="OFF" />
</ViewFlipper>

To make it look slightly prettier, you can also define the animations to be used in the viewFlipper:

<ViewFlipper
    android:id="@+id/viewFlipper1"
    android:autoStart="true"
    android:flipInterval="3000"
    android:inAnimation="@android:anim/fade_in"
    android:outAnimation="@android:anim/fade_out">    

AdapterViewFlipper Documentation.

Timer t = new Timer();
    TimerTask scanTask = new TimerTask() {
        public void run() {
            mHandler.post(new Runnable() {
                        public void run() {
                            mSwitcher.setText(isOn ? "ON" : "OFF");  
                            isOn = isOn? false : true;
                        }
               });
        }};

    t.schedule(scanTask, 0, 2000); 

I change the UI, use the handler. Make the handler variable private to the Activity and call handler.sendEmptyMessage().

You can use thread or Async task to call the Handler.sendEmptyMessage(ON/OFF).

One more way is to use Handler.sendEmptyMessageDelayed ( ) . By this handler invokes itself after every time the user has set in delayed value.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!