android - Kotlinx 从错误的布局中注入(inject) View

标签 android kotlin kotlin-android-extensions

我有一段代码检查 View 是否可见

import kotlinx.android.synthetic.main.activity_layout.*

val isOverflowPanelShown: Boolean
   get() = overflow_panel.visibility != View.GONE

前面的代码抛出异常

java.lang.ClassCastException: android.widget.FrameLayout cannot be cast to android.widget.ScrollView
    at com.company.app.Activity.isOverflowPanelShown(Activity.kt:362)

View 是 ScrollView 类的实例,但是 kotlin 认为它是一个 FrameLayout。在抛出错误的同一位置调用 findViewById() 它会正确返回 ScrollView。我发现在应用程序的不同布局中有一个 FrameLayout 在相同的 id 下

我正在按照布局充气

activity_layout

<ScrollView
    android:id="@+id/overflow_panel"
    android:layout_width="300dp"
    android:layout_height="wrap_content"
    />

在我在完全不同的地方使用的另一个布局中,有一个具有相同 ID 的不同 View 。

form_component_main

<FrameLayout
    android:id="@+id/overflow_panel" 
    android:layout_width="250dp"
    android:layout_height="wrap_content"
    />

最佳答案

为什么不给他们不同的 ID?

overflow_panel_scroll
overflow_panel_frame

或者更能描述他们实际所做的事情。

更新:在这被否决后,有更多的解释。 ID 应该是唯一的。

Android 文档说,如果 ID 不是唯一的,可能会发生冲突:ID 不必在整个树中是唯一的,但它在您正在搜索的树的部分内应该是唯一的(这可能通常是整棵树,因此最好尽可能完全唯一。(来自 http://developer.android.com/guide/topics/ui/declaring-layout.html )

Kotlin 合成器由 IntelliJ 插件生成。如果 ID 不是唯一的,插件目前似乎无法将 ID 正确匹配到正确的 View 。它可能需要唯一的 ID。

关于android - Kotlinx 从错误的布局中注入(inject) View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38338943/

相关文章:

没有花括号的 Kotlin 类

android - AIDL : Incompatible types: Object cannot be converted to MyCustomObject 中的 Parcelize 注释

android - 如何读取android中的Nfc标签?

android - react native java.security.cert.CertPathValidatorException : Trust anchor for certification path not found

KTX 安卓动画

android-studio - 如何在Kotlin Android中为屁股添加+/-功能

android - 当我在 android studio 中添加导航时,出现 "Build gradle start up"错误和 "unable to resolve class val :13"错误

Android Chrome - 按键事件不返回任何关键数据(jQuery)?

java - Android - 创建适配器时出现 NullPointerException

arrays - Kotlin 类型不匹配 : inferred type is Int? 但预期为 Int