【问题标题】:Element is given wrong id元素的 ID 错误
【发布时间】:2014-07-08 22:12:31
【问题描述】:

在闲置的 xml 中,我将 LinearLayout 设置为 @+id/camera,但是当我调用 (LinearLayout) findViewById(R.id.camera) 时,我得到了 ClassCastException: Button can not be cast to Linearlayout。换句话说,id 是如何应用于其中一个按钮的。如果我删除第二个android:layout_above="@+id/camera",那么它工作正常。这是怎么回事?

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <LinearLayout
        android:id="@+id/camera"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true" />
    <View 
        android:id="@+id/center"
        android:layout_height="match_parent"
        android:layout_width="0dp"
        android:visibility="invisible"
        android:layout_centerHorizontal="true" />
    <Button
        android:id="@+id/front"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="front"
        android:layout_alignParentLeft="true"
        android:layout_toLeftOf="@+id/center"
        android:layout_above="@+id/camera" />
    <Button
        android:id="@+id/back"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="back"
        android:layout_alignParentRight="true"
        android:layout_toRightOf="@+id/center"
        android:layout_above="@+id/camera" />
    <Button
        android:id="@+id/export"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="export"
        android:layout_alignParentBottom="true"
        android:layout_below="@+id/camera" />
</RelativeLayout>

【问题讨论】:

  • 再次确认您没有意外导入android.R

标签: android xml android-relativelayout


【解决方案1】:
<Button
    android:id="@+id/front"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="front"
    android:layout_alignParentLeft="true"
    android:layout_toLeftOf="@+id/center"
    android:layout_above="@+id/camera" />

第二次提及+ 时,不应使用它。 android:id="@+id/my_id" 表示“我正在将此 ID 添加到 ID 列表中,我想将其用作此元素的 id。”

android:id="@id/my_id" 的意思是“我想用一个现有的 id 作为这个元素的 id。”

【讨论】:

  • 请忽略我之前的评论。我必须做一个干净的构建,一定是缓存了旧版本。
【解决方案2】:

需要解决的两件事:

  1. 当引用 layout_x 约束中的元素时,删除 +

  2. 确保您没有意外导入android.R

【讨论】:

  • 我没有导入android.R
  • re:第 1 点,并非总是如此。考虑一个 RelativeLayout,您将在其中引用尚未在 XML 布局中声明的元素(即下面的元素)。在这种情况下,您将拥有“+”,而在将 ID 分配给元素时,您将不会拥有它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-19
  • 2017-04-29
  • 2020-03-10
  • 1970-01-01
  • 2023-03-27
  • 2017-02-28
相关资源
最近更新 更多