Unresolved reference - activity does not recognize synthetic imports in android studio v4

Viewed 1470
4 Answers

Kotlin Synthetic imports not working ?

Well, there's always the age-old alternative:

val foo: TextView = findViewById(R.id.your_id)

I believe synthetics have been deprecated and I guess support for it has just now been completely removed


Alternatively, you can make use of ViewBinding, which is another alternative.

Enable it in your build.gradle:

android {
    ...
    buildFeatures {
        viewBinding true
    }
}

This generates a Binding object for your layout, so you can make use of it like this:

private lateinit var binding: YourLayoutNameBinding

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

then you have access to all views on the layout, through the binding:

binding.name.text = "foo"

An alternative you can look at is ViewBinding, a concept in Android that was introduced recently.

You should take a look for this

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

You cannot set view id directly for your use in app, instead you need findViewById(R.id.idTextHello).setOnClickListener()

That's how views are bind in application.

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

but dont forget to apply kotlin extension

You are trying to access your views via Kotlin Synthetics, which have been deprecated. You can use ViewBinding instead.

Enable it in your module level build.gradle:

android {
...
buildFeatures {
    viewBinding true
}
}

And then in your activity you can access views like :

private lateinit var _binding: ActivityNameBinding

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    _binding = ActivityNameBinding(layoutInflater)
    val view = binding.root
    setContentView(view)
}

and then you can access your views like this:

_binding.btn_start.setOnClickListener {
...
}

For detailed understanding of ViewBinding, you can look into this article:

https://medium.com/geekculture/android-viewbinding-over-findviewbyid-389401b41706

Related