我知道Google的Material Design指南建议不要使用ProgressDialog,而是使用其他不那么干扰的方式来显示进度,但我需要将ProgressDialog用于我应用的特定活动。
所以,问题是我想在DialogFragment中包含一个ProgressDialog,因此我的代码如下:
public class MaterialProgressDialogFragment extends DialogFragment {
private int total;
private MaterialDialog myDialog;
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return myDialog;
}
public void incrementProgress(int by) {
myDialog.incrementProgress(by);
}
public void setTotal(int total) {
this.total = total;
}
public void setUp(Context context) {
myDialog = new MaterialDialog.Builder(context)
.title("Progress")
.content("Processing...")
.progress(false, total, true)
.build();
}
}
因为我想构建的是一个确定的ProgressDialog,我希望能够在我的应用程序的生命周期内更新其进度。为此,我创建了一个名为setProgress(progress)的方法,但myDialog始终为null,以及getDialog()返回的值。
我做错了什么?
谢谢
编辑:我在片段的onCreateActivity()方法中显示对话框,如下所示:MaterialProgressDialogFragment dialogFragment = new MaterialProgressDialogFragment();
dialogFragment.setTotal(100);
dialogFragment.setUp(getActivity());
dialogFragment.show(getSupportFragmentManager(), "");
dialog.incrementProgress(50);
所有内容都按预期工作,直到最后一行,这会导致应用程序抛出异常。
答案 0 :(得分:0)
dialog
方法中的变量setProgress(int progress)
是什么并不完全清楚。但如果你的意思是getDialog()
,那么按对话框片段创建对话需要时间,而dialogFragment.show(getSupportFragmentManager(), "")
和onCreateDialog(Bundle savedInstanceState)
回调之间会有一些时间间隔,在此期间{{1} }将返回getDialog()
。
编辑:
好的,现在更清楚了。但是通过上面的代码,你违反了片段框架规则。您应该使用null
方法创建对话框,否则您将遇到生命周期问题(例如,如果您将旋转屏幕,应用程序将崩溃)。
我建议你使用类似的东西:
onCreateDialog(Bundle savedInstanceState)
您应该将public class MaterialProgressDialogFragment extends DialogFragment {
public static final String TOTAL_KEY = "total";
public static ProgressDialogFragment newInstance(int total) {
Bundle args = new Bundle();
args.putInt(TOTAL_KEY, total);
ProgressDialogFragment pdf = new ProgressDialogFragment();
pdf.setArguments(args);
return pdf;
}
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
MaterialDialog myDialog = new MaterialDialog.Builder(context)
.title("Progress")
.content("Processing...")
.progress(false, getTotal(), true)
.build();
return myDialog;
}
public void incrementProgress(int by) {
if (getDialog()!=null)
((MaterialDialog)getDialog()).incrementProgress(by);
}
public int getTotal() {
return getArguments().getInt(TOTAL_KEY);
}
}
变量保存到参数中,因为它会在配置更改时被销毁(例如屏幕旋转)。
然后通过以下方式创建并显示:
total
如果您想更改进度,请致电:
MaterialProgressDialogFragment dialogFragment = MaterialProgressDialogFragment.newInstance(100);
dialogFragment.show(getSupportFragmentManager(), "");
但请记住,对话框不会立即创建,所以如果你在show()之后调用它,它将不会生效,因为dialog.incrementProgress(50);
将返回null。如果您只想测试它,请将其称为延迟:
getDialog()
但无论如何,在真正的应用程序中,您将从一些后台进程中改变您的进度。