New to kotlin & android. I have a button and ...
# getting-started
c
New to kotlin & android. I have a button and when it is clicked, I display a toast. I want to format the toast before I display it. I wanted to do something like Toast.makeText().setGravity().show() but setGravity doesn't return the toast to show, so it seems I can either define a toast variable to setup before I show it or for chaining, I could use .also{}. Just wondering if there are any pluses or minuses of each method or what is the "Kotlin way?" Thanks. Here is code for both ways I set it up.
Copy code
trueButton.setOnClickListener {
            val toast = Toast.makeText(
                this,
                R.string.correct_toast,
                Toast.LENGTH_SHORT
            )
            toast.setGravity(<http://Gravity.TOP|Gravity.TOP>, 0 , 200)
            toast.show()
        }

        falseButton.setOnClickListener {
            Toast.makeText(
                this,
                R.string.incorrect_toast,
                Toast.LENGTH_SHORT
            ).also {
                it.setGravity(<http://Gravity.TOP|Gravity.TOP>, 0, 200)
            }.show()
        }
i
#android
c
sorry, I wasn't sure if this was an android question or a getting started question, more related to the kotlin piece than android so I guessed this channel.
a
@CBedzz You can use something like this
Copy code
with(Toast.makeText(requireActivity(), "", Toast.LENGTH_SHORT)) {
            setGravity(<http://Gravity.TOP|Gravity.TOP>, 0, 200)
            show()
        }
👍🏾 1
2
c
Thanks, a third way! definitely reads better!
n
Or use apply instead of also because that makes the object available via this and thus allows to write
Copy code
Toast.makeText(requireActivity(), "", Toast.LENGTH_SHORT).apply {
   <http://setGravity.TOP|setGravity.TOP>, 0, 200)
   }.show()