Update The Ui With Dynamic Text
Solution 1:
I would use a Handler.
privatestaticfinalintWHAT=1;
privatestaticfinalintTIME_TO_WAIT=5000;
HandlerregularHandler=newHandler(newHandler.Callback() {
publicbooleanhandleMessage(Message msg) {
// Do stuff
regularHandler.sendEmptyMessageDelayed(msg.what, TIME_TO_WAIT);
returntrue;
}
});
regularHandler.sendEmptyMessageDelayed(WHAT, TIME_TO_WAIT);
As an example, that would "Do stuff" every 5000 milliseconds. You can make the Handler react to different events by passing in WHAT as a different integer and handling that in the handleMessage function.
Edit: I would normally place the constants and the Handler in the class as members and the regularHandler.sendEmptyMessageDelayed(...) in onResume() {}
I would also put this in onPause() {}
regularHandler.removeMessages(WHAT)
Edit2: Example:
publicclassHomeActivityextendsActivityimplementsOnClickListener {
privatestaticfinalintWHAT=1;
privatestaticfinalintTIME_TO_WAIT=5000;
publicvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textTitle = (TextView) findViewById(R.id.textTitle);
textArtist = (TextView) findViewById(R.id.textArtist);
}
@OverridepublicvoidonResume() {
super.onResume();
regularHandler.sendEmptyMessageDelayed(WHAT, TIME_TO_WAIT);
}
@OverridepublicvoidonPause() {
super.onPause();
regularHandler.removeMessages(WHAT);
}
HandlerregularHandler=newHandler(newHandler.Callback() {
publicbooleanhandleMessage(Message msg) {
// Do stuff
regularHandler.sendEmptyMessageDelayed(msg.what, TIME_TO_WAIT);
returntrue;
}
});
}
You need to do it in onResume() and onPause() because if you don't put it in onPause the Handler will continue to loop while your Activity isn't in the foreground. You will want the loop to enable again when it comes back to the foreground (hence onResume()).
Solution 2:
Using a handler is a good strategy but you don't really need a custom callback. Instead you can just use postDelayed
with a Runnable
. See this Android doc for details on implementation.
Solution 3:
runOnUiThread(new Runnable() {
publicvoidrun() {
textTitle.setText(title);
}
});
You cannot update UI from background thread. Whenever you want to make modifications to UI it is suggested to use UI thread
Post a Comment for "Update The Ui With Dynamic Text"