我有这个 ModalProgress 类,我在每个地方都使用它来显示模态进度,我想你可以按原样使用它:
public class ModalProgress extends DialogFragment {
public static void show(Activity activity, String title,
String message) {
if (activity == null) {
return;
}
FragmentManager fm = activity.getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
hideInternal(ft, fm);
// Create and show the dialog.
DialogFragment newFragment = new ModalProgress();
Bundle args = new Bundle();
args.putString("title", title);
args.putString("message", message);
newFragment.setArguments(args);
newFragment.show(ft, "dialog");
}
private static void hideInternal(FragmentTransaction ft, FragmentManager fm) {
Fragment prev = fm.findFragmentByTag("dialog");
if (prev != null) {
ft.remove(prev);
}
}
public static void hide(FragmentActivity activity) {
if (activity == null) {
return;
}
FragmentManager fm = activity.getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
hideInternal(ft, fm);
ft.commit();
}
public ModalProgress() {
setCancelable(false);
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Bundle args = getArguments();
ProgressDialog dialog = new ProgressDialog(getActivity());
String title = args.getString("title");
String msg = args.getString("message");
if (!TextUtils.isEmpty(title)) {
dialog.setTitle(title);
}
if (!TextUtils.isEmpty(msg)) {
dialog.setMessage(msg);
}
return dialog;
}
}
现在将循环代码移动到 AsyncTask 中:
private class LongTask extends AsyncTask<Void, Void, Void> {
protected void onPreExecute (){
ModalProgress.show(getActivity(), "Working", "Please wait...");
}
protected Void doInBackground(Void... voids) {
for (int i = 0; i < count; i++) {
// your loop here
}
return null;
}
protected void onPostExecute(Void result) {
ModalProgress.hide(getActivity());
}
}
然后执行AsyncTask
.