问题描述
- 使用动态文本更新 UI出现的问题
-
我想每5秒钟更新一次屏幕上的文本,就创建了一个 timer 计时器来实现。但是只有第一次更新了,以后再没更新。是不是我需要刷新视图或者使用别的方法?public class HomeActivity extends Activity implements OnClickListener { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); textTitle = (TextView) findViewById(R.id.textTitle); textArtist = (TextView) findViewById(R.id.textArtist); timedMeta(); } static void timedMeta() { timer.scheduleAtFixedRate( new TimerTask() { public void run() { try{ textTitle.setText(title); textArtist.setText(artist); } Thread.sleep(UPDATE_INTERVAL); catch (Exception e) { }, DELAY_INTERVAL, UPDATE_INTERVAL); } } ) }
解决方案
要使用一个 Handler.
private static final int WHAT = 1;
private static final int TIME_TO_WAIT = 5000;
Handler regularHandler = new Handler(new Handler.Callback() {
public boolean handleMessage(Message msg) {
// Do stuff
regularHandler.sendEmptyMessageDelayed(msg.what, TIME_TO_WAIT);
return true;
}
});
regularHandler.sendEmptyMessageDelayed(WHAT, TIME_TO_WAIT);
onPause()
regularHandler.removeMessages(WHAT)
解决方案二:
你可以在activity中开一个线程,里面放个while循环,线程每sleep5秒就通过handler更新一次UI,记住,不能在activity的子线程中更新UI,否则会报错
时间: 2024-11-03 06:01:09