我希望能在我的应用程序下载一些大文件时展示一个进度条,显示完成的百分比,就像这样:
。
![enter image description here](https://istack.dev59.com/flJB2.webp)
XML文件代码:
<ProgressBar
android:id="@+id/xml_reg_progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/common_left_right_margin"
android:layout_marginRight="@dimen/common_left_right_margin"
android:layout_marginTop="@dimen/reg_ph_linear_top_margin"
/>
protected static final int TIMER_RUNTIME = 180000; // in ms --> 10s
private ProgressBar progressTimer;
public void startTimer() {
final Thread timerThread = new Thread() {
@Override
public void run() {
mbActive = true;
try {
int waited = 0;
while (mbActive && (waited < TIMER_RUNTIME)) {
sleep(1000);
if (mbActive) {
waited += 1000;
updateProgress(waited);
}
}
} catch (InterruptedException e) {
// do nothing
} finally {
onContinue();
}
}
};
timerThread.start();
}
Handler handler = new Handler();
private void onContinue() {
handler.post(new Runnable() {
@Override
public void run() {
txtCallContactUsNumber
.setText(CommonVariable.CallForSupporMessage
+ contactInfo.MobileNo);
}
});
}
public void updateProgress(final int timePassed) {
if (null != progressTimer) {
// Ignore rounding error here
final int progress = progressTimer.getMax() * timePassed
/ TIMER_RUNTIME;
handler.post(new Runnable() {
@Override
public void run() {
Log.i("timePassed", "timePassed=" + timePassed);
DateFormat formatter = new SimpleDateFormat("mm:ss");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(timePassed);
String timer = formatter.format(calendar.getTime());
formatter.setTimeZone(java.util.TimeZone.getTimeZone("GMT"));
txtTimerCount.setText(formatter.format(timePassed));
}
});
progressTimer.setProgress(progress);
}
}
请查看以下链接:
http://examples.javacodegeeks.com/android/core/ui/progressdialog/android-progressdialog-example/
这些链接清晰地解释了如何实现ProgressBar
或ProgressDialog
以下是一个很好的自定义ProgressDialog库:
你应该使用进度条。
我假设你正在使用Asynctask来下载文件,如果你没有使用,我建议你使用它。
Async task除了
doInBackground()
还有两个很酷的方法
preExecute和postExecute
你可以重写这些方法,现在创建一个简单的进度条,在preExecute方法中启动它,在postExecute方法中结束它。
这里是工作LINK。