2012-12-15 227 views
1

我知道你只能从UI线程更改tTxtViews中的文本,但我似乎找不到一种方法来处理这个问题。从线程更改TextView文本

我会介绍一些细节:我试图让TextView显示时间已过,但我无法在一个线程或一个不断调用的方法中执行此操作。 你能帮助我做到这一点吗?因为我几乎没有想法。

谢谢。

+0

那么,如果你知道你不能做到这一点,你一定是试过的东西吗?在这里发布你的试验,也许我们可以帮助你找出你出错的地方。 –

+0

A-C说什么,它取决于你想从哪里改变TextView。 – Christine

回答

2
 public class MainActivity extends Activity { 

      protected static final long TIMER_DELAY = 100; 
      private TextView tv; 
      protected Handler handler; 

      @Override 
      protected void onCreate(Bundle savedInstanceState) { 
       super.onCreate(savedInstanceState); 
       setContentView(R.layout.activity_main); 

       tv = (TextView)findViewById(R.id.helloWorld); 
       handler = new Handler(); 
       handler.post(timerTask); 


      } 

      private Runnable timerTask = new Runnable() { 
       public void run() { 
        Calendar now = Calendar.getInstance(); 

        //format date time 
        tv.setText(String.format("%02d:%02d:%02d", now.get(Calendar.HOUR_OF_DAY), now.get(Calendar.MINUTE), now.get(Calendar.SECOND))); 

        //run again with delay 
        handler.postDelayed(timerTask, TIMER_DELAY); 
       } 
      }; 


     } 

我忘了添加这个,对不起。不要忘了这样做:

@Override 
    public void onPause() { 

     if (handler != null) 
      handler.removeCallbacks(timerTask); 

     super.onPause(); 
} 

如果你想恢复应用程序尝试这个

@Override 
    public void onResume() { 
     super.onResume(); 

     if (handler != null) 
      handler.post(timerTask); 
} 
+0

非常感谢你! amaxing解决方案! – Yuval3210

1

使用此

new Thread(new Runnable() { 

    @Override 
    public void run() { 
     runOnUiThread(new Runnable() { 

      @Override 
      public void run() { 
       // Do what you want. 
      }   
     }); 
    }   
}).start(); 

或使用Handler

Runnable r = new Runnable() { 

    @Override 
    public void run() { 
     // Do what you want. 
    } 
}; 
Handler mHandler = new Handler(); 
mHandler.post(r);