Dialog dialog;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(R.layout.progress);
// This should be called once in your Fragment's onViewCreated() or in Activity onCreate() method to avoid dialog duplicates.
dialog = builder.create();
}
// This method is used to control the progress dialog.
private void setDialog(boolean show){
if (show)dialog.show();
else dialog.dismiss();
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="20dp">
<ProgressBar
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="4"
android:gravity="center"
android:text="Please wait! This may take a moment." />
</LinearLayout>
下一步是创建AlertDialog,它将用ProgressBar显示这个布局
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setCancelable(false); // if you want user to wait for some process to finish,
builder.setView(R.layout.layout_loading_dialog);
AlertDialog dialog = builder.create();
现在剩下的就是在点击事件中显示和隐藏这个对话框
这样的< / p >
dialog.show(); // to show this dialog
dialog.dismiss(); // to hide this dialog