如何每2秒在两个值之间连续切换textswitcher [英] how to continuously switch textswitcher between two values every 2 seconds

查看:107
本文介绍了如何每2秒在两个值之间连续切换textswitcher的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看过代码此处,但我似乎仍然无法正确执行我的代码.通过第二个链接,我可以在页面上获得一个计时器",但在第一个链接中,我的用户界面已锁定.我想要做的是有一个单独的线程,只要打开该应用程序,它就会每3秒连续翻转一次文本切换器中的文本.我需要它在两个值之间切换,并尝试了以下操作:

I've looked at the code here as well as the code here but I still can't seem to get my code to work right. With the 2nd link, I can get a "timer" that counts up on the page, but with the first, my UI locks up. What I'm trying to do is have a seperate thread that continually flips the text in a textswitcher every 3 seconds as long as the app is open. I need it to switch between two values, and have tried something like the following:

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

             } 
                 }
             };

每2秒钟翻转一次开"或关"的位置.我还需要能够从主UI更新文本切换器的内容,但是还没有到可以尝试进行测试的地步.除了上述内容之外,我还尝试了使用异步任务:

Where it will flip "on" or "off" every 2 seconds. I also need to be able to update the text switcher content from the main UI, but haven't gotten to the point i can try and test that. In addition to the above, I have also tried to use an Async Task:

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

但这也不起作用.

推荐答案

尝试使用

runOnUiThread的引用.您无法从非ui线程更新gui元素,因此尝试从AsyncTaskdoInBackground()方法更新它会导致错误.

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.

这篇关于如何每2秒在两个值之间连续切换textswitcher的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆