0

So I have an Alert Dialog with custom view. I set it up in a different class form my fragment.

I have the same problem with this question. The .show() is executed successfully but the .dismiss() wont't work, so the Dialog is still there even when dismiss() is called.

This is the class where i set up my Alert Dialog

class LoadingDialog(val currentContext: Context) {

   val loadingDialogLayout = LayoutInflater.from(currentContext).inflate(R.layout.loading_dialog_layout, null)

    val loadingDialog = AlertDialog
            .Builder(currentContext)
            .setView(loadingDialogLayout)
            .setCancelable(false)
            .create()


    fun show() {
        loadingDialog.show()
    }


    fun dismiss() {
        loadingDialog.dismiss()
    }
}

And this is how I call it in my fragment

....

LoadingDialog(activity as AppCompatActivity).show() <- Here

    EHealthServiceClient.eHealthInstance.requestPickup(orderId).enqueue(object : Callback<DefaultResponse> {
        override fun onFailure(call: Call<DefaultResponse>, t: Throwable) {

            LoadingDialog(activity as AppCompatActivity).dismiss() <- Here

            ...
        }

        override fun onResponse(call: Call<DefaultResponse>, response: Response<DefaultResponse>) {

            LoadingDialog(activity as AppCompatActivity).dismiss() <- Here

            if (response.code() == 200) {
                ...
            } else {
               ...
            }

        }
    })
}

Did I miss something ? If there's anything I forgot to mention, feel free to ask. Thank you.

dimas hermanto
  • 369
  • 7
  • 22

1 Answers1

0

The problem is that you are instantiating a new LoadingDialog class every time, and with that, you are creating a new AlertDialog instance.

Change your LoadingDialog class to an object like this

object LoadingDialog {

    lateinit var loadingDialog: AlertDialog

    fun show(activity: Activity) {
        val loadingDialogLayout = LayoutInflater.from(activity).inflate(R.layout.loading_dialog_layout, null)
        this.loadingDialog = AlertDialog
            .Builder(activity)
            .setView(loadingDialogLayout)
            .setCancelable(false)
            .create()

        loadingDialog.show()
    }


    fun dismiss() {
        if (::loadingDialog.isInitialized) {
            loadingDialog.dismiss()
        }
    }
}

Then you can simply call

LoadingDialog.show(<your-context>)

and

LoadingDialog.dismiss()
lpizzinidev
  • 12,741
  • 2
  • 10
  • 29