Home > front end >  How can I pass a Fragment to a context parameter?
How can I pass a Fragment to a context parameter?

Time:12-26

I have this function and I'd like to call it within a fragment.

fun showProgressBar(context: Context) : ProgressDialog {
        val progressDialog = ProgressDialog((context))
        progressDialog.isIndeterminate = true
        progressDialog.setMessage(context.getString(R.string.progress_loading))
        progressDialog.show()
        return progressDialog
    }

That's how I call in an activity: val mProgressDialog = Utils.showProgressBar(this@MainActivity) Calling it in a fragment val mProgressDialog = Utils.showProgressBar(this@HomeFragment) throws this error

enter image description here

CodePudding user response:

The Fragment class has many methods. One of these is requireContext(), which will attempt to give you a Context to use. This will only work while the fragment is attached to an activity.

CodePudding user response:

A Fragment has methods getActivity() and getContext() (or just activity and context in Kotlin). To get a context from a Fragment, you just need to do

Utils.showProgressBar(activity)
// or
Utils.showProgressBar(context) 

Note that activity or context can be null depending on when in the lifecycle you call it. To require a non-null context/activity you can use

val ctx = requireContext()
// or
val act = requireActivity()

which will either return a non-null activity (context) or throw and IllegalStateException

  • Related