package com.margelo.nitro.progressandmodal import android.app.Activity import android.view.Gravity import android.view.ViewGroup import android.widget.FrameLayout import android.widget.ProgressBar import android.content.res.ColorStateList import androidx.core.graphics.toColorInt class PAMLoadingManager(private val getActivity: () -> Activity?) { private val loadingViewTag = 9999 private var loadingCount: Int = 0 private var backgroundColor: String = "#29000000" private var indicatorColor: String = "#666666" fun setConfig(backgroundColor: String?, indicatorColor: String?) { backgroundColor?.let { this.backgroundColor = it } indicatorColor?.let { this.indicatorColor = it } } fun showLoading() { val activity = getActivity() ?: return activity.runOnUiThread { loadingCount++ if (loadingCount == 1) { val rootView = activity.window.decorView as ViewGroup // Remove existing if present rootView.findViewWithTag(loadingViewTag)?.let { rootView.removeView(it) } val loadingView = FrameLayout(activity).apply { tag = loadingViewTag setBackgroundColor(backgroundColor.toColorInt()) isClickable = true isFocusable = true layoutParams = FrameLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ).apply { gravity = Gravity.CENTER } } val progressBar = ProgressBar(activity).apply { layoutParams = FrameLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT ).apply { gravity = Gravity.CENTER } indeterminateTintList = ColorStateList.valueOf(indicatorColor.toColorInt()) } loadingView.addView(progressBar) rootView.addView(loadingView) ViewUtils.fadeIn(loadingView) } } } fun hideLoading() { val activity = getActivity() ?: return activity.runOnUiThread { if (loadingCount > 0) { loadingCount-- if (loadingCount == 0) { removeLoadingView(activity) } } } } fun forceHideLoading() { val activity = getActivity() ?: return activity.runOnUiThread { loadingCount = 0 removeLoadingView(activity) } } private fun removeLoadingView(activity: Activity) { val rootView = activity.window.decorView as ViewGroup rootView.findViewWithTag(loadingViewTag)?.let { view -> ViewUtils.fadeOut(view) { rootView.removeView(view) } } } }