如何每2秒在两个值之间连续切换文本切换器

Eva*_* R. 4 multithreading android background while-loop

我已经查看了这里的代码 以及这里的代码, 但我仍然无法让我的代码正常工作.使用第二个链接,我可以获得一个在页面上计数的"计时器",但是第一个,我的UI锁定.我想要做的是有一个单独的线程,只要应用程序打开,它就会每3秒钟在文本切换器中不断翻转文本.我需要它在两个值之间切换,并尝试过以下内容:

private Runnable mUpdateTimeTask = new Runnable() {


       public void run() {
           while(true){                                                             
                try {
                    mHandler.post(new Runnable(){
                       @Override
                       public void run() {

                          try {
                            mSwitcher.setText("ON");  
                            Thread.sleep(1000);
                            mSwitcher.setText("OFF");
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                       }
                    }
                    ); 

                }catch (Exception e) {
                    //tv1.setText(e.toString());
                }

             } 
                 }
             };
Run Code Online (Sandbox Code Playgroud)

它每2秒钟会"开启"或"关闭".我还需要能够从主UI更新文本切换器内容,但还没有达到我可以尝试测试的程度.除了上述内容之外,我还尝试使用异步任务:

      new AsyncTask<Void, Double, Void>() {
      @Override
      protected Void doInBackground(Void... params) {
          while (true) {
              mSwitcher.setText("ON");
                SystemClock.sleep(2000);
                mSwitcher.setText("OFF");
                SystemClock.sleep(2000);
          } 
      }     
  }.execute();
Run Code Online (Sandbox Code Playgroud)

但这也行不通.

Ror*_*ory 5

另一种更容易实现这一目标的方法是使用a viewFlipper而不是a viewSwitcher.这允许您单独使用XML布局执行所需的所有操作:

<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>
Run Code Online (Sandbox Code Playgroud)

为了使它看起来更漂亮,您还可以定义要在以下位置使用的动画viewFlipper:

<ViewFlipper
    android:id="@+id/viewFlipper1"
    android:autoStart="true"
    android:flipInterval="3000"
    android:inAnimation="@android:anim/fade_in"
    android:outAnimation="@android:anim/fade_out">    
Run Code Online (Sandbox Code Playgroud)

AdapterViewFlipper文档.


Vla*_*mir 2

尝试使用计时器

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);
Run Code Online (Sandbox Code Playgroud)

runOnUiThread 的参考。您无法从非 ui 线程更新 gui 元素,因此尝试从doInBackground()方法更新它AsyncTask会导致错误。