未解决的参考 - 活动无法识别 android studio v4 中的合成导入

未解决的参考 - 活动无法识别 android studio v4 中的合成导入

问题描述:

昨晚我注意到我无法从我的主要活动中更改布局中元素的属性所以我建立了一个新项目,我在那里也遇到了同样的问题.我无法找出我的 android 工作室出了什么问题,所以如果有同样问题的人帮助我,我将不胜感激.正如您在图片中看到的,当我从我的活动中的布局调用定义的视图时,它无法识别 错误将是:未解析的引用:txtHello

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

Kotlin Synthetic 导入不起作用?

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

或者,您可以使用 ViewBinding,这是另一种选择.

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

在你的 build.gradle 中启用它:

Enable it in your build.gradle:

android {
    ...
    buildFeatures {
        viewBinding true
    }
}

这会为您的布局生成一个 Binding 对象,因此您可以像这样使用它:

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"