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.
}
3 Likes
jpaone
October 14, 2019, 8:06pm
2
4 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()
}
2 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
CBedzz
January 24, 2020, 4:26pm
6
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?
2 Likes
Sophro
April 10, 2020, 8:51pm
7
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()
}
}
1 Like
Чтобы я ни делал, а сообщение не меняет своего положения…
falseButton.setOnClickListener {
Toast.makeText(
this,
R.string.incorrect_toast,
Toast.LENGTH_SHORT
).apply {
setGravity(Gravity.CENTER,0,0)
}.show()
}
trueButton.setOnClickListener {
val toast = Toast.makeText(
this,
R.string.correct_toast,
Toast.LENGTH_SHORT
)
toast.setGravity(Gravity.TOP,0,0)
toast.show()
}