Using Views
suggest changeAssuming we have an activity with an example layout called activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>
We can use Kotlin extensions to call the button without any additional binding like so:
import kotlinx.android.synthetic.main.activity_main.my_button
class MainActivity: Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// my_button is already cast to Button, not View
my_button.setText("Kotlin rocks!")
}
}
You can also import every id in the layout with *:
// my_button can be used the same way as before
import kotlinx.android.synthetic.main.activity_main.*
Synthetic views can’t be used outside of Activities/Fragments/Views with that layout inflated:
import kotlinx.android.synthetic.main.activity_main.my_button
class NotAView {
init {
// This sample won't compile!
my_button.setText("Kotlin rocks!")
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents