Yes, there is a way to handle this in Kotlin for an Android Studio project without having to manually use findViewById for each individual view. This is achieved using Kotlin Android Extensions (KAE).
However, as of Kotlin 1.4.20, the Kotlin Android Extensions plugin is deprecated and Jetpack ViewBinding is recommended.
Here is how to generate all the findViewById using Jetpack ViewBinding:
- First, enable viewBinding in your build.gradle (Module: app) file:
android {
...
viewBinding {
enabled = true
}
}
- Then, you can use ViewBinding to reference views:
import com.example.yourapp.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
// you can access your views directly
binding.yourViewId
}
}
Just replace yourViewId with the id of your view. With this, you don't need to use findViewById anymore.
Please note that the name ActivityMainBinding is generated based on the name of the XML file. So if your XML file name is activity_main.xml, the generated Binding class will be ActivityMainBinding.
The Kotlin Android Extensions (KAE) would be as follows:
import kotlinx.android.synthetic.main.your_layout.*
class YourActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.your_layout)
yourViewId // directly access your view
}
}
Replace your_layout with the name of your XML layout file and yourViewId with the id of your view.
Remember to sync your gradle files after making these changes.