Android: Display element of array with time delay?

1.5k views Asked by At

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?

1

There are 1 answers

1
jeet parmar On

Try this code :

public class test extends Activity {

private TextView textView;
private int i = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.test);
    textView = (TextView)findViewById(R.id.text);
    set();
}
private void set(){

    final String text ="A n d r o i d P r o g r a m m i n g";
    final String[] words = text.toString().split(" ");
    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, 1000);
            }
        }
    });
}}