开发者

ProgressBar in Android: having trouble getting it to work

In my activity, I set up my progress bar as follows:

bar = (ProgressBar) findViewById( R.id.download_progress_bar );
bar.setProgress( 0 );
bar.setMax( 100 );

I have a runnable that updates both some text, and the progress bar. The text updating works fine, but the progress bar does not. Here is the runnable:

private class Update开发者_C百科Download implements Runnable
{
    private int downloadSize;

    public UpdateDownload( int downloadSize )
    {
        this.downloadSize = downloadSize;
    }

    public void run()
    {
        textDownloaded.setText( String.format( "%d / %d kB", downloadSize / 1024, currentFileSize / 1024 ) );
        textTotalDownloaded.setText( String.format( "%d / %d kB", ( downloadSize + bytesSoFar ) / 1024, totalSize / 1024 ) );
        bar.setSecondaryProgress( downloadSize / currentFileSize / 100 );
        bar.setProgress( ( downloadSize + bytesSoFar ) / totalSize / 100 );
    }
}


Your math is wrong. The value put into setProgress must be between 0 and max, which is 100 in your case.

So:

bar.setProgress( 100 * ( downloadSize + bytesSoFar ) / totalSize );


Just go through this article: http://developer.android.com/resources/articles/painless-threading.html.

I suggest you to use AsyncTask , here is link for more information regarding the AsyncTask: http://developer.android.com/reference/android/os/AsyncTask.html.

Now, amongst the 4 methods which we can use inside AsyncTask, use onProgressUpdate() as below to update progress bar value.

protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜