I'm writing an Android layout using Anko DSL.
When defining a TextView
, I wanted to make it center-aligned, so I wrote this:
verticalLayout {
textView(R.string.txt_greeting).apply {
gravity = Gravity.CENTER_HORIZONTAL // <- this should have changed the alignment
textSize = 20.0f
}
//...
}
But the alignment didn't change. In debugger I saw that gravity is set for the LinearLayout
which is the TextView
's parent.
Changing the statement to either
textView(R.string.txt_greeting).let { it.gravity = Gravity.CENTER_HORIZONTAL }
and
textView(R.string.txt_greeting).apply { [email protected] = Gravity.CENTER_HORIZONTAL }
and even
textView(R.string.txt_greeting).apply { this.gravity = Gravity.CENTER_HORIZONTAL }
solves the problem, thus in the original code implicit this
is definitely resolved to this@verticalLayout
.
Why does this happen?
Do I misunderstand something in Kotlin lambdas or is it a bug in Kotlin or Anko?
It was actually a bug in scoping.
The corresponding issue has been marked as fixed, so the fix is likely to appear in the next release.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With