布局中的 android:id 字段错误不再被识别
在 android 项目中将 android-studio、kotlin 插件和 sourceCompatibility 升级到 Java 8 后,许多布局 id 不再被识别(但奇怪的是不是全部)。 看起来带下划线的字段名称在绑定中无法识别。
例如: 布局中的以下声明
<TextView
android:id="@+id/alert_hist_item__equipement"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5px"
android:text="@string/Device"
android:textStyle="bold"
/>
代码中
alert_hist_item__equipement.text = "x"
无法识别,但
alertHistItemEquipement.text = "x"
可以识别。
如果我将布局中的字段名称更改为等效的驼峰式名称(仅在代码中,布局中的名称仍带有下划线;或者在代码和布局中),则字段将被识别。
由于多种原因,这非常痛苦:
- 我有几十个布局,所有的 id 名称都包含下划线
- 我发现带有下划线的名称更容易阅读(我的团队也是如此)
- 从未指定 android:id 字段应该遵循某些规则,
这可能吗改变这种行为?这可能是一个错误吗?
Following an upgrade of android-studio, kotlin plugins and sourceCompatibility to Java 8 in an android project, many layout ids are not any more recognized (but strangely not all).
It looks like field name with underscores are not recognized in binding.
For instance:
whith the following declaration in the layout
<TextView
android:id="@+id/alert_hist_item__equipement"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5px"
android:text="@string/Device"
android:textStyle="bold"
/>
in the code
alert_hist_item__equipement.text = "x"
is not recognized but
alertHistItemEquipement.text = "x"
is recognized.
If I change the field names in the layouts to equivalent camel case names (either only in the code, with the names in the layout still having underscores; or both in code and layout) the fields are recognized.
It is so painful for many reasons:
- I have dozens of layouts all with id names containing underscore
- I find names with underscore easier to read (and my team too)
- it was never specified that android:id fields should follow certain rules
is this possible to change that behavior ? Could it be a bug ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请将以下
id 'kotlin-android-extensions'
添加到您的应用级别 gradle。根据 Kotlin 文档,它们已被弃用,但它们仍然为我工作。
作为替代,它们为我们提供数据和视图绑定。对于您来说,
View Binding
应该可以工作!这是示例:
将以下内容添加到您的应用程序级别 gradle:
然后在您的活动中声明如下(假设您的活动名称是 ManuelYguel)
Please add following
id 'kotlin-android-extensions'
to you app level gradle.According to Kotlin documentation they are deprecated but they are still working for me.
As and alternate they provide us with data and view binding. For you
View Binding
should work!here is the example:
add following to your app level gradle:
then in you activity declare as following (Assuming you activity name is ManuelYguel)
这是来自新的自动生成的绑定类的悲伤和不幸的约束。这是在 https://developer.android.com/topic/libraries/ 中指定的数据绑定/表达式
它说:
It is a sad and unfortunate constraint that comes from the new autogenerated binding class. This is specified in https://developer.android.com/topic/libraries/data-binding/expressions
it says: