我有一段代码检查 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。我发现在应用程序的不同布局中,在同一id 下存在一个 FrameLayout
。我正在扩大以下布局
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不唯一,则可能会发生冲突:
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与正确的 View 正确匹配。可能需要唯一的ID。