Android独立于Activity或者Fragment的LoadingDialog的实现
public class LoadDialogMgr { private static final String LOAD_TIP_DIALOG_TAG = "LoadTipDialog"; private static LoadDialogMgr sMLoadDialogMgr; private LoadDialogMgr() { } public static LoadDialogMgr instance() { if (sMLoadDialogMgr == null) { sMLoadDialogMgr = new LoadDialogMgr(); } return sMLoadDialogMgr; } public void showDialog(FragmentActivity activity) { FragmentManager manager = activity.getSupportFragmentManager(); LoadTipDialog loadTipDialog; Fragment fragment = manager.findFragmentByTag(LOAD_TIP_DIALOG_TAG); if (fragment instanceof LoadTipDialog) { loadTipDialog = (LoadTipDialog) fragment; } else { loadTipDialog = LoadTipDialog.newInstance(); } if (loadTipDialog.isAdded()) { return; } manager.beginTransaction() .remove(loadTipDialog) .add(loadTipDialog, LOAD_TIP_DIALOG_TAG) .commitAllowingStateLoss(); } public void closeDialog(FragmentActivity activity) { FragmentManager manager = activity.getSupportFragmentManager(); LoadTipDialog loadTipDialog; Fragment fragment = manager.findFragmentByTag(LOAD_TIP_DIALOG_TAG); if (fragment instanceof LoadTipDialog) { loadTipDialog = (LoadTipDialog) fragment; loadTipDialog.dismissAllowingStateLoss(); } } public void showDialog() { Activity activity = ActivityUtil.getTopActivity(); if (activity instanceof FragmentActivity) { showDialog((FragmentActivity) activity); } } public void closeDialog() { Activity activity = ActivityUtil.getTopActivity(); if (activity instanceof FragmentActivity) { closeDialog((FragmentActivity) activity); } } }
public class LoadTipDialog extends AppCompatDialogFragment {
private View mRootView;
public static LoadTipDialog newInstance() {
Bundle args = new Bundle();
LoadTipDialog fragment = new LoadTipDialog();
fragment.setArguments(args);
return fragment;
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
mRootView = inflater.inflate(R.layout.dialog_load_tip, container, false);
return mRootView;
}
}
//R.layout.dialog_load_tip
<?xml version="1.0> encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:padding="15dp"
android:background="#999999"
android:gravity="center"
android:orientation="vertical">
<ProgressBar
android:id="@+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:text=" loading..."
android:textColor="@color/black"
android:textSize="16sp"/>
</LinearLayout>