Search code examples
javaandroidtextview

How to print array elements in textview with a delay


I am trying to print all the elements of an Array of Strings one by one in the same textview with 1 second delay between each element, but the only thing is printed is the last element.

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;


public class MainActivity extends AppCompatActivity {
    private TextView tv2;
    private String []numbers={"1","2","3","4","5"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv2=findViewById(R.id.tv2);
    }

    public void initiate(View view){

        for (int i = 0; i < numbers.length; i++){
                    tv2.setText(numbers[i]);
                    tv2.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            tv2.setText("");
                        }
                    },1000);
        }
    }
}

Solution

  • Try This

    UPDATE

    public void initiate(View view){
         int i = 0;
         new CountDownTimer((number.lenght*10000),1000){
    
                               @SuppressLint("SetTextI18n")
                               @Override
                               public void onTick(long millisUntilFinished) {
                                    if(i<numbers.length)
                                       tv2.setText(numbers[i++]);
                               }
    
                               @Override
                                public void onFinish() {
                               
                                }
                          }.start();
    }