我正在为学校做一个小文件管理器,我试图让它在将文件粘贴到新位置时显示进度。我怎样才能让它这样做呢?我知道如何在对话框中设置进度,但您将使用什么文件?目前进度条的最大值是用户试图粘贴的文件数,但这只在用户粘贴多个文件时有效,而不是一个文件。是否有一种方法来更新进度条的数量与粘贴的字节数或类似的东西?
代码:
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < mClipboard.size(); i++) {
final int index = i;
// Copy, or cut, each file or directory into the destination directory
final File newFile = copy(getFile(i), dest, false);
scanImage(newFile, context);
context.runOnUiThread(new Runnable() {
@Override
public void run() {
// Update the adapter and increment the progress dialog
if (newFile != null) adapter.add(newFile);
// Increment the progress dialog
dialog.setProgress(index);
}
});
}
context.runOnUiThread(new Runnable() {
@Override
public void run() {
// Remove paste option from action bar
context.invalidateOptionsMenu();
// Clear the clipboard
clear();
// Close the dialog
dialog.dismiss();
}
});
}
}).start();
我想你对android比较陌生,有一个类叫做异步任务。您可以使用i来运行任何后台操作。当对话框在后台运行时显示对话框就像这样简单:
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private ProgressDialog mProgressDialog;
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Loading..");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
然后写一个异步任务来更新进度。
private class DownloadZipFileTask extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
@Override
protected String doInBackground(String... urls) {
//Your background task code here.
publishProgress("" + progress);
}
protected void onProgressUpdate(String... progress) {
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
@Override
protected void onPostExecute(String result) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
您必须使用异步任务在后台粘贴文件。下面是一个很好的代码示例:http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html
Android dowumenation:http://developer.android.com/reference/android/os/AsyncTask.html