2

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 tried, but the result is that I see only the last update of the loop, so I get "100%" with no incremntation.

    runOnUiThread(new Runnable() {
                         public void run() {
                            final TextView progesss = (TextView)findViewById(R.id.progress);
                            for(int k=1 ; k<=100; k++)
                            {
                                progesss.setText(String.valueOf(k) + "%");

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

Any ideas of how to achieve my goal? Thanks!

4

2 回答 2

2

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:

final Handler handler = new Handler();
handler.post( new Runnable(){ 
    private int k = 0;

    public void run() {
        final TextView progess = (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.

于 2012-12-28T19:21:00.217 回答
0

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]+");
}

}



}
于 2012-12-28T19:27:52.317 回答