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

查看:73
本文介绍了无法解析的参考-活动无法识别android studio v4中的合成导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

昨晚我注意到我无法从主要活动中更改布局中元素的属性 所以我建立了一个新项目,在那里我也遇到了同样的问题. 我无法找出我的android studio出了什么问题,所以如果有相同问题的人帮助我,我将不胜感激. 您在图片中看到的,当我从活动中的布局调用已定义的视图时,该视图未被识别 错误将是:未解析的引用: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 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天全站免登陆