在Android studio中使用RelativeLayout布局时候,在对控件使用android:layout_toLeftOf=""属性,
会出现Error:(26, 34) No resource found that matches the given name (at 'layout_toLeftOf'
with value '@id/button2'). r文件被删除。代码如图
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.framic.relativelayout3.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:id="@+id/textView"
android:layout_centerInParent="true"/>
<Button
android:text="现在更新"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button"
android:layout_below="@id/textView"
android:layout_toLeftOf="@id/button2"
/>
<Button
android:text="以后再说"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button2"
android:layout_toRightOf="@id/button"
android:layout_alignRight="@id/textView"
android:layout_below="@id/textView"/>
</RelativeLayout>
错误原因分析:
布局文件本来就是xml,虚拟机解析的时候从上到下解析,使用对应控件id时,该控件要先被声明。该实例中先加载的是button,button的layout_toLeftOf
属性关联到了button2,而button2未被声明,所以会出现找不到button2的错误。