2

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

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)

视图是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 的不同视图。

form_component_main

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

1 回答 1

2

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

overflow_panel_scroll
overflow_panel_frame

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

更新:更多解释,因为这被否决了。ID 应该是唯一的。

Android 文档说,如果 ID 不是唯一的,可能会发生冲突:(An ID need not be unique throughout the entire tree, but it should be unique within the part of the tree you are searching (which may often be the entire tree, so it's best to be completely unique when possible).来自http://developer.android.com/guide/topics/ui/declaring-layout.html

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

于 2016-07-12T21:14:42.043 回答