在我的应用程序中,我正在下载一个视频文件。我想显示下载进度条。
如何通过 AsyncTask 概念实现?
谢谢,
尼基
最佳答案
使用AsyncTask的onProgressUpdate方法。
如果您知道文件的大小,您可以在 onPreExecute 中设置最大值:
protected void onPreExecute() {
ProgressDialog myDialog = new ProgressDialog(context);
myDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
myDialog.setMax(maxValue);
myDialog.show();
}
编辑:添加 myDialog.show();
有几种方法可以更新进度,可以通过递增一定量或将进度设置为特定值:
@Override
protected void onProgressUpdate(Integer... progress) {
myDialog.incrementProgressBy(progress[0]);
// or
// myDialog.setProgress(progress[0]);
}
然后在 onDoInBackground() 中:
@Override
protected void doInBackGround() {
// your code
publishProgress(1);
}
在布局中使用进度条编辑示例:
在你的布局文件中,添加一个这样的进度条
<ProgressBar
android:id="@+id/progressbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="?android:attr/progressBarStyleHorizontal"
android:visibility="gone"
/>
在你的异步任务中:
protected void onPreExecute() {
ProgressBar myProgress = findViewById(R.id.progressbar);
myProgress.setMax(maxValue);
myProgress.setVisibility(View.VISIBLE);
}
protected void onProgressUpdate(Integer... progress) {
myProgress.setProgress(progress[0]);
}
关于android - 如何给下载一个进度条?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5296424/