未解决的参考 - 活动无法识别 android studio v4 中的合成导入 [英] Unresolved reference - activity does not recognize synthetic imports in android studio v4

查看:22
本文介绍了未解决的参考 - 活动无法识别 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"

这篇关于未解决的参考 - 活动无法识别 android studio v4 中的合成导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆