Toast Challenge Solution with a Question

https://developer.android.com/guide/topics/ui/notifiers/toasts.html

 trueButton.setOnClickListener { view : View ->
           val toast= Toast.makeText(this,
                R.string.correct_toast,
                Toast.LENGTH_LONG)
            toast.setGravity(Gravity.TOP,0,0)
            toast.show()  }

Seems that you cannot just call .show() + .setGravity and you have to set it to a variable. Can somebody explain why it doesn’t concatenate?

    //Seems logical, doesn't work
 trueButton.setOnClickListener { view : View ->
    Toast.makeText(this,
                    R.string.correct_toast,
                    Toast.LENGTH_LONG)
          .setGravity(Gravity.TOP,0,0)
          .show() // Android Studio starts to complain when you write this line.
  }
1 Like

setGravity() returns void (nothing) and does not follow the builder model.

https://developer.android.com/reference/android/widget/Toast.html#setGravity(int,%20int,%20int)

makeText() does return a Toast object which any Toast method can be called upon (setGravity() or show())

https://developer.android.com/reference/android/widget/Toast.html#makeText(android.content.Context,%20int,%20int)

1 Like