Reputation: 19
Usually we do not use findViewById (R.id.listView) in kotlin because Android studio do it for us automatically (we do not need to find view). But this example shows that we need to you it (in this line of code):
val listView = findViewById<ListView>(R.id.listView) as ListView.
Why do we use this line in this example? How to not use it?
Upvotes: 0
Views: 7237
Reputation: 2846
It's only applicable for Kotlin
Step 1: Add this Kotlin Android Extensions in our code
Gradle Scripts -> build.gradle(Module)
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
NOTE: Now you can directly access the view id without using findViewbyId, in case if you face any red line press alt+enter, or import this in KT file.
import kotlinx.android.synthetic.main.activity_your_layout.*
Upvotes: 1
Reputation: 89548
If you're using findViewById
from Kotlin, you should never need a cast (from API level 26 and up). You should use it one of these two ways:
val myTV1 = findViewById<TextView>(R.id.myTextView)
val myTV2: TextView = findViewById(R.id.myTextView)
And then you can access its properties via these variables:
myTV1.text = "testing"
This is a perfectly valid way of getting View references and using them in Kotlin as it is.
However, if you also have Kotlin Android Extensions enabled in the project (by the apply plugin: 'kotlin-android-extensions'
line in your module level build.gradle
file), you also can refer to your Views by their IDs via the synthetic properties it provides, just make sure you have the correct imports, for example:
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
myTextView.text = "testing"
}
}
Note that Kotlin Android Extensions is entirely optional to use, and if you do use it, findViewById
of course is still available if for whatever reason you want to mix the two methods.
Upvotes: 8
Reputation: 1088
In general, when you need a view from a layout file, you can import the following:
kotlinx.android.synthetic.main.<layout filename>.<id of view>
If you need all of the views from a layout file, you can use:
kotlinx.android.synthetic.main.<layout filename>.*
Upvotes: 1