【Android初级】如何实现一个“模拟后台下载”的加载效果(附源码)

在Android里面,后台的任务下载功能是非常常用的,比如在APP Store里面下载应用,下载应用时,需要跟用户进行交互,告诉用户当前正在下载以及下载完成等。

今天我将通过使用Android的原生控件 ProgressDialog 来实现一个“模拟后台下载”的效果。实现思路如下:

  1. 用户点击按钮,模拟开始下载

  2. 显示一个进度框,并修改后台界面上的文字,告知用户当前正在下载、需要等待

  3. 开启一个线程,模拟后台下载任务,假设下载需要3秒钟完成,让该线程等待3秒

  4. 线程执行完成后,关闭进度框,并更新界面上的文字,告知用户下载完成

源码如下:

1、主Activity

`public class ProgressDialogDemo extends Activity {
private Button button;
private TextView textView;
private ProgressDialog mDialog;

@Override
protected void onCreate(Bundle onSavedInstance) {
super.onCreate(onSavedInstance);
setContentView(R.layout.progress_dialog_demo);

button = findViewById(R.id.buttonProgressDialog);
textView = findViewById(R.id.textView6);

button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

// 创建并显示进度加载框
mDialog = ProgressDialog.show(ProgressDialogDemo.this,
"Please wait..",
"Calculating in the background...",
true);

// 设置文字内容,告诉用户当前正在后台计算
textView.setText("Calculating in the background...");

new Thread() {
@Override
public void run() {
try {

// 模拟耗时的后台计算
sleep(3000);
} catch (InterruptedException e) {

} finally {

// 耗时的后台计算完成,关闭进度框,再次以文字的形式告诉用户
mDialog.dismiss();
refreshTextView();
}
}
}.start();
}
});
}

private void refreshTextView() {
textView.post(new Runnable() {
@Override
public void run() {

// 需要在主线程去重新设置文字
textView.setText("Done with calculating.");
}
});
}
}`

2、布局文件progress_dialog_demo.xml:

`


posted @ 2021-01-27 22:38  snowyeti  阅读(384)  评论(0)    收藏  举报