Update Textview With Each String In String-array Every 5 Seconds
I have a TextView and I would like to update the TextView every 5 second with each string in my String Array. Here is the code I tried. It always shows only the last String in the
Solution 1:
final String[] wc = {"The", "Qucik", "Brown", "fox", "Jumped"};
final android.os.Handlerhandler=newandroid.os.Handler();
handler.post(newRunnable() {
inti=0;
@Overridepublicvoidrun() {
display.setText(wc[i]);
i++;
if (i == wc.length) {
handler.removeCallbacks(this);
} else {
//5 sec
handler.postDelayed(this, 1000 * 5);
}
}
});
Solution 2:
- Problem: The last iteration of the for-loop (on j) sets the text to the last string.
You need to make sure that you call TextView.setText()
only once per tick. Then you can go with your approach (CountDownTimer
) or with Antrrommet's (Handler
). With your approach, this will look like something like:
intcounter=0; // field member, NOT local variable@OverridepublicvoidonTick(long millisUntilFinished) {
display.setText("{" + wc[counter++] + "}");
if (counter == 5) counter = 0;
}
Solution 3:
If the answer is useful. Please do vote :)
final String[] gritArray = getResources().getStringArray(R.array.gritInformation);
//creating new handler allows send and process messagefinalHandlergritInfoHanlder=newHandler();
//adding runnable to message queque
gritInfoHanlder.post(newRunnable() {
//initializing array positioninttipPosition=0;
@Overridepublicvoidrun() {
//set number of tip(randon/another way)//setting array to textview
gritInfo.setText(gritArray[tipPosition]);
tipPosition++;
//if array exist its length remove callbackif (tipPosition == gritArray.length) {
gritInfoHanlder.removeCallbacks(this);
//delayed handler 10 sec
} else {
gritInfoHanlder.postDelayed(this, 1000 * 10);
}
}
});
Post a Comment for "Update Textview With Each String In String-array Every 5 Seconds"