【问题标题】:Using dots in xml ids在 xml id 中使用点
【发布时间】:2016-11-24 11:06:39
【问题描述】:

这是我的第一个问题

在 Java 中我从来没有遇到过这个问题。

我花了两天时间,因为我遇到了一个问题只是在设计模式上在 Android 工作室使用 kotlin 为 CustomView 充气。膨胀后我有一个 findByView = null 。运行应用程序,一切正常

View.inflate(context, R.layout.widget_navigation_section_button, this) 
mLabel = findViewById(R.id.navigation_section_title)
mLabel.setText("something")

这会引发 NPE (在 kotlin 中是真实的:kotlin.TypeCastException:null 不能在 ... $mLabel$2.invoke(CustomView.kt:22) 处转换​​为非空类型 android.widget.TextView )

通常,我使用<layout>[.<where_container>].<name> 模式来命名 XMls 上的 id 和字符串(例如:android:id="@+id/main.description_container.title"
这是在代码中的R.id.main_description_container_title(注意点变成下划线)中自动翻译的

当我在 XML 中手动将这些点替换为下划线时,问题已解决

我一直在寻找名称约定来解释为什么不应该在 id 或字符串命名中使用点,但没有成功。我想知道这个命名约定的真正问题是什么。这真的应该避免吗?

我应该放弃这个想法而只是用户下划线吗?看看它只是在 kotlin 上的一个问题,也许是一些 gradle 配置?

提前谢谢你

【问题讨论】:

标签: android xml android-studio kotlin


【解决方案1】:

您不能使用点,因为下面的表达式R.id.main.description_container.title 将尝试查找类型为Int 的成员main,然后尝试查找属性description_container,但Int 没有这样的属性

【讨论】:

  • 好的,但是当您启动应用程序时,它运行良好。这只是 Android Studio 的设计预览模式 + kotlin 的问题。使用 Java 也可以
  • @cgarrido 我认为,使用点是个坏主意,但欢迎您打开错误报告(无论如何,Kotlin 不受官方支持)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-04
  • 1970-01-01
  • 2013-04-01
  • 1970-01-01
相关资源
最近更新 更多