Android 元素的id错误

Android 元素的id错误,android,xml,android-relativelayout,Android,Xml,Android Relativelayout,在休闲xml中,我将LinearLayout设置为@+id/camera,但当我调用(LinearLayout)findViewById(R.id.camera)时,我得到了一个ClassCastException:按钮无法转换为LinearLayout。换句话说,id是如何应用于其中一个按钮的。如果我删除上面的第二个android:layout_=“@+id/camera”,那么它可以正常工作。这是怎么回事 <?xml version="1.0" encoding="utf-8"?>

在休闲xml中,我将LinearLayout设置为
@+id/camera
,但当我调用
(LinearLayout)findViewById(R.id.camera)
时,我得到了一个
ClassCastException:按钮无法转换为LinearLayout
。换句话说,id是如何应用于其中一个按钮的。如果我删除上面的第二个
android:layout_=“@+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:id=“@+id/my_id”
表示“我正在将此id添加到id列表中,并希望将其用作此元素的id。”

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

需要解决两件事:

  • 在引用
    布局\u x
    约束中的元素时,请删除
    +

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


  • 仔细检查您是否无意中导入了
    android.R
    。我没有导入
    android.R
    re:第1点,情况并非总是如此。考虑一个ReleLayayOutlook,在这里你指的是XML布局中还没有声明的元素(即下面的元素)。在这种情况下,您将拥有“+”,而在为元素分配ID时,您将不会拥有它。请忽略我之前的评论。我必须做一个干净的构建,一定是缓存了旧版本。
    <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" />