skip to Main Content

I just started learning App development with Android Studio and Kotlin, but I have a problem. In the tutorial, it is possible to access a textView from the main XML file in the main kotlin file by just writing the id of the textView. But it is not working for me. The id does not get recognised in the kotlin file, but in the video it does. I already checked if the id is correct and I have followed every step in the video.

Example:

myTextView.text = "text of myTextView"

Thanks for help in advance!

2

Answers


  1. It requires kotlin-android-extensions but it is deprecated. So recent Android Studio may not add the required plugin to your build.gradle. You still can use it by manually adding apply plugin: 'kotlin-android-extensions' to build.gradle (In addition, import is required in your kt file but the IDE will automatically do it) but it is not recommended. Instead use view binding, as explained in this official docs: https://developer.android.com/topic/libraries/view-binding

    Login or Signup to reply.
  2. If you’re using old version of Android studio then can use

    id 'kotlin-android-extensions
    

    and import the following in Kotlin file

    import kotlinx.android.synthetic.main.activity_main.*
    

    then you can directly refer to the all views that have an ID.

    But if you are using latest version of Android studio then (id ‘kotlin-android-extensions) will not work as this method is deprecated. Instead what we can do is,
    add following code in gradle file.

    plugins {id 'kotlin-android-extensions'}
    

    and

    android {
    ...
    buildFeatures {
        viewBinding true}
    }
    

    do the following in kotlin file ( for every XML file, a Binding class will be generated for example- in case of activity_main.XML binding class will be ActivityMainBinding):

    private lateinit var binding: ActivityMainBinding
    
    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityMainBinding.inflate(layoutInflater)
    val view = binding.root
    setContentView(view)}
    

    and how to refer any ID from XML

    // Reference to "name" TextView using synthetic properties.
    name.text = viewModel.nameString
    
    // Reference to "name" TextView using the binding class instance.
    binding.name.text = viewModel.nameString
    

    For More detail, you can follow these links –
    https://developer.android.com/topic/libraries/view-binding/migration#groovy

    https://developer.android.com/topic/libraries/view-binding#kotlin

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search