我希望每5秒钟更新一次屏幕上的文本,为此我创建了一个计时器.但是,在第一次更新后,它再也不会更新该框.我假设我需要刷新视图或其他内容,但现在确定如何,有什么想法?
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); } } )}
解决方法:
我会使用处理程序.
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);
例如,这将每隔5000毫秒“执行任务”.通过将WHAT作为不同的整数传入并在handleMessage函数中进行处理,可以使Handler对不同的事件做出反应.
编辑:通常,我会将常量和Handler作为成员,并在onResume(){}中将regularHandler.sendEmptyMessageDelayed(…)放置在类中
我也将其放在onPause(){}中
regularHandler.removeMessages(WHAT)
Edit2:示例:
public class HomeActivity extends Activity implements OnClickListener { private static final int WHAT = 1; private static final int TIME_TO_WAIT = 5000; public voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentVIEw(R.layout.main); textTitle = (TextVIEw) findVIEwByID(R.ID.textTitle); textArtist = (TextVIEw) findVIEwByID(R.ID.textArtist); } @OverrIDe public voID onResume() { super.onResume(); regularHandler.sendEmptyMessageDelayed(WHAT, TIME_TO_WAIT); } @OverrIDe public voID onPause() { super.onPause(); regularHandler.removeMessages(WHAT); } Handler regularHandler = new Handler(new Handler.Callback() { public boolean handleMessage(Message msg) { // Do stuff regularHandler.sendEmptyMessageDelayed(msg.what, TIME_TO_WAIT); return true; } });}
您需要在onResume()和onPause()中执行此 *** 作,因为如果不将其放在onPause中,则当您的Activity不在前台时,处理程序将继续循环.您需要使循环在回到前台时再次启用(因此onResume()).
总结以上是内存溢出为你收集整理的android-用动态文本更新UI全部内容,希望文章能够帮你解决android-用动态文本更新UI所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)