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

五迷三道 提交于 2021-02-13 05:40:42

问题


last night I noticed I'm not able to change the attributes of elements in the layout from my main activity so I built a new project and I had the same problem there too. I could not find out what was wrong with my android studio so I'd appreciate it if someone with the same problem helps me out. as you see in the picture when I call a defined view from the layout in my activity its not recognized the error will be: Unresolved reference: txtHello


回答1:


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"



回答2:


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.



来源:https://stackoverflow.com/questions/64716903/unresolved-reference-activity-does-not-recognize-synthetic-imports-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!