Reputation: 13
I have a simple program with one button. Once I clicked on the button loop started and should display the current value in TextView dynamically. But this display the value when loop is completed.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=(TextView) findViewById(R.id.textView2);
}
public void btnClick(View v) throws Exception {
for (int i=0;i<10;i++){
tv.setText("Value of I "+i);
Thread.sleep(500);
}
}
My expected output is displaying values from 0, 1,.... dynamically but displayed 9 at last. if I use append I have to wait until loop terminated. Please help me.
Upvotes: 0
Views: 739
Reputation: 4856
Try this:
int i = 0; //declare this globally
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
if(i != 10) {
text.append(" " + i);
i++;
handler.postDelayed(this, 1000);
}
}
}, 1000);
}
Make sure you declare int i = 0
globally
Upvotes: 2
Reputation: 98
don't use Thread.sleep() in your main UI thread this should give an exception instead use a new Thread like this
Thread myThread = new Thread(new Runnable() {
@Override
public void run() {
for (int i=0;i<10;i++){
tv.setText("Value of I "+i);
Thread.sleep(500);
}
}
});
myThread.start();
or if there is more complex operations you make you will have to use AsyncTask calss
Upvotes: 0