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.
  }
4 Likes

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)

5 Likes

I would like to write it in the Kotlin approach.

My answer for this challenge is

trueButton.setOnClickListener { view ->
            Toast.makeText(this, R.string.correct_toast, Toast.LENGTH_SHORT)
                .also { it.setGravity(Gravity.TOP, 0, 0) }
                .show()
        }

falseButton.setOnClickListener { view ->
            Toast.makeText(this, R.string.incorrect_toast, Toast.LENGTH_SHORT)
                .also { it.setGravity(Gravity.TOP, 0, 0) }.show()
        }
3 Likes

Thanks, for your solution. I wasn’t able to get solution of the first challenge of the 4th edition android programming book.

1 Like

I like naag’s solution, since it seems more functional, but also came up with one using with instead of also that I think is more readable.

            falseButton.setOnClickListener {
                with(Toast.makeText(this, R.string.incorrect_toast, Toast.LENGTH_SHORT)) {
                    setGravity(Gravity.TOP, 0, 200)
                    show()
                }
            }

Are there any performance implications or other pluses and minuses to any of the approaches?

3 Likes

Building on CBedzz solution and inspired by the BNR Kotlin programming book, I used ‘.run’ iso ‘with’ ->

    trueButton.setOnClickListener {
        Toast.makeText(
            this,
            R.string.correct_toast,
            Toast.LENGTH_SHORT
        ).run {
            this.setGravity(Gravity.TOP,0,0)
            this.show()
        }
    }

    falseButton.setOnClickListener {
        Toast.makeText(
            this,
            R.string.incorrect_toast,
            Toast.LENGTH_SHORT
        ).run {
            this.setGravity(Gravity.TOP, 0, 0)
            this.show()
        }
    }
2 Likes