While working on a larger project, I wanted to display all elements of a String array with a time delay (so as to be readable by the user).
In my example, I have a StringBuilder text
that is split on tabs and stored in String[] words
.
My initial idea was to use something like:
String[] words = text.toString().split("\t");
for (String word : words) {
textView.setText(word);
SystemClock.sleep(2000);
}
However, this blocks the UI thread and thus only shows the last value. After reading up abit more, I came up with this solution (which works):
final String[] words = text.toString().split("\t");
final Handler handler = new Handler();
handler.post(new Runnable(){
@Override
public void run() {
textView.setText(words[i]);
i++;
if(i < words.length) {
handler.postDelayed(this, TIME_DELAY_MS);
}
}
});
However, this requires me to have i
as a private variable of the class (declaring it in the same scope as the handler forces it to be final, which it can't be in order to go through the array).
Having a private variable of the class just for this purpose seems very inelegant - is there any better way of doing this that I missed?
Try this code :