Codist
Codist

Reputation: 769

How to show toast on a fragment in Kotlin?

I am not able to show a toast on a fragment. It shows the error as in the screenshot. I am using kotlin. Please advice.

enter image description here

Error message

enter image description here

Upvotes: 0

Views: 678

Answers (1)

sergeych
sergeych

Reputation: 869

Use Fragment's activity. You can use extension function to easily produce toasts in fragments:

fun Fragment.makeToast(text: String,duration: Int = Toast.LENGTH_LONG) {
    activity?.let {
        Toast.makeText(it, text, duration).show()
    }
}

Now in the Fragment you can just use it like:

class LoginFragment : Fragment() {
   //...
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        //...

        makeToast("lets start")


Upvotes: 1

Related Questions