-1

I have a custom progress bar class that I want to convert to an extension function so that i can use it any where in the project (Both fragment and activity) without initialising.

I want to be able to inflate the progress bar layout in the function and also have the one to dismiss the progress bar.

How can i do this?

class CustomProgressDialog(context: Context) : AlertDialog(context) {
    private val messageTextView: TextView

    init {
        val view = LayoutInflater.from(context).inflate(R.layout.layout_loading_dialog, null)
        messageTextView = view.findViewById(R.id.message)
        setView(view)
    }

    override fun setMessage(message: CharSequence?) {
        this.messageTextView.text = message.toString()
    }

    fun showProgressDialog(message: String) {
        this.setMessage(message)
        this.setCanceledOnTouchOutside(false)
        this.setCancelable(false)
        this.show()
    }

    fun hideProgressDialog() {
        this.dismiss()
    }
}
Oluwafemi
  • 306
  • 1
  • 4
  • 14
  • Unclear what you're trying to do. A class and a function are completely different things. You can't use a class without initializing it either. – Tenfour04 Jun 21 '21 at 17:29
  • I just want to make the two function `showProgressDialog()` and `hideProgressDialog` an extension of something like Fragment.showProgressDialog()... But i get some error that i don't understand yet. – Oluwafemi Jun 21 '21 at 17:44
  • 1
    You can't do that because extensions can't store state. The `hide` function will have no way of retrieving the instance of Dialog created by the `show` function. You could however make the `show` function return the dialog instance so you can store it in a property in each of your Fragments and use that to hide it. – Tenfour04 Jun 21 '21 at 17:49

1 Answers1

0

Do something like this

class ResultDialog(context: Context) : Dialog(context) {
    
    companion object {
            fun show(context: Context): ResultDialog {
                var resultDialog: ResultDialog? = null
                try {
                    resultDialog = ResultDialog(context)
                    resultDialog.show()
    
                } catch (ex: Exception) {
                    ex.printStackTrace()
                }
                return resultDialog!!
            }
        }
    }

Then call showing this dialog from fragment following way

ResultDialog.show(requireContext)

Also you can have extension function

fun Fragment.showDialog():ResultDialog{
    return ResultDialog.show(requireContext())
}

If you have a base Fragment class you can put method there also