Search code examples
androidfor-looptextview

Android setText TextView in For-loop


button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            for (int i = 0; i<5; i++) {

                textview.setText("loop test" + i);

                try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                
            }
        }
    });

How can I get setText to run every time the loop turns? This is the code I tried. However, this only prints the final result.


Solution

  • There are a few things wrong with your code: First, you are tying up the main thread with the Thread.sleep(100) statement. That is something that your code should not do. Second, you delay is so short that it happens so quickly (0.1 seconds) that you will miss it.

    Try the following code and do some investigation to understand it better and to decide on an approach you want to take.

    // Wait for the layout to complete.
    textview.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
        @Override
        public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    if (++i < 5) {
                        textview.setText("loop test " + i);
                        new Handler(Looper.getMainLooper()).postDelayed(this, 500);
                    }
                }
            });
        }
    });