I do it that way:
This is the class with the dialog fragment:
class FullscreenLoadingDialog : DialogFragment() {
private lateinit var binding: DiaogLoadingBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = DiaogLoadingBinding.inflate(layoutInflater)
dialog?.requestWindowFeature(Window.FEATURE_NO_TITLE)
return binding.root
}
override fun onStart() {
super.onStart()
dialog?.window?.apply {
setBackgroundDrawableResource(android.R.color.transparent)
setLayout(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
}
}
companion object {
const val TAG = "FullscreenLoadingDialog"
}
}
the XML view diaog_loading.xml
:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ProgressBar
android:id="@+id/progressIndicator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:indeterminate="true"
android:indeterminateTint="@color/purple_200" />
</FrameLayout>
Then you could show/hide from anywhere that you have access to a FragmentManager.
I made two Kotlin extension functions:
showing like this:
fun FragmentManager.showLoading() {
// Check if the dialog is already added or visible
val existingDialog = findFragmentByTag(FullscreenLoadingDialog.TAG) as? FullscreenLoadingDialog
if (existingDialog == null || !existingDialog.isAdded) {
// Dialog is not added yet, now we can show it
FullscreenLoadingDialog().show(this, FullscreenLoadingDialog.TAG)
}
}
hiding like this:
fun FragmentManager.hideLoading() {
(findFragmentByTag(FullscreenLoadingDialog.TAG) as? FullscreenLoadingDialog)
?.run { dismiss() }
}