Android Loop Update Textview
I am trying to create a loop that will update a TextView. The idea is to create some sort of progress indicator, that will increment the loading precentge. This is what I have trie
Solution 1:
Your Runnable
blocks the UI thread when doing Thread.sleep
. Instead of sleeping, you should post a new Runnable
again. Try with something like this:
finalHandlerhandler=newHandler();
handler.post( newRunnable(){
privateintk=0;
publicvoidrun() {
finalTextViewprogess= (TextView)findViewById(R.id.progress);
progess.setText(String.valueOf(k) + "%");
k++;
if( k <= 100 )
{
// Here `this` refers to the anonymous `Runnable`
handler.postDelayed(this, 15);
}
}
});
That will give the UI thread a chance to run between each call, letting it do its stuff like handling input and drawing stuff on the screen.
Solution 2:
You use background thread and UI Thread.
public class testAsync extends AsyncTask<Void, Integer, Voi>{
TextView progress; // You will set TextView referans
protected void doInBackground(){
for(int k=1 ; k<=100; k++)
{
try {
Thread.sleep(1000);
publishProgress(k);
} catch(InterruptedException e) {}
}
}
protected void onProgressUpdate(Integer.. values)
{
progress.setText(values[0]+");
}
}
}
Post a Comment for "Android Loop Update Textview"