0

I have the following function that display a custom toast

fun showCustomToast() {
        val inflater = layoutInflater
        val container: ViewGroup = findViewById(R.id.toastContainer)
        val layout: ViewGroup = inflater.inflate(R.layout.custom_toast, container) as ViewGroup
        val text: TextView = layout.findViewById(R.id.textView)
        text.text = "This is a custom toast"
        with (Toast(applicationContext)) {
            setGravity(Gravity.CENTER_VERTICAL, 0, 0)
            duration = Toast.LENGTH_LONG
            view = layout
            show()
        }
}

I am calling this function on main activity just below setContentView(R.layout.activity_main)When running the application I am getting the following error

Caused by: java.lang.IllegalStateException:
> findViewById(R.id.toastContainer) must not be null

What am I doing wrong . . .
I have come across this but it doesn't help

Mehul Kabaria
  • 6,404
  • 4
  • 25
  • 50
Emmanuel Mtali
  • 4,383
  • 3
  • 27
  • 53

2 Answers2

1

The function findViewById() will search for views within your Activity's layout and not any other specific views you might have declared. Is your container inside another View?

samlo
  • 113
  • 10
1
val container: ViewGroup = findViewById(R.id.toastContainer)
val layout: ViewGroup = inflater.inflate(R.layout.custom_toast, container) as ViewGroup

In your comments you write toastContainer is in custom_toast layout. It cannot be found in the current layout (assuming it's an activity).

You don't actually need a container for inflater, and since the toast is not yet showing there wouldn't be any real container available anyway yet. You can replace these two lines with something like

val layout = inflater.inflate(R.layout.custom_toast, null)
laalto
  • 150,114
  • 66
  • 286
  • 303