Android开发报错:layout_above引用@id/adView找不到对应资源
解决Android布局中
No resource found that matches the given name (at 'layout_above' with value '@id/adView')报错 嘿,这个问题我之前也碰到过,其实核心原因就是XML控件的声明顺序导致的!
问题根源
在RelativeLayout中,Android系统是从上到下解析XML布局的。你的fragment_container控件里用了android:layout_above="@id/adView"来引用adView,但adView的定义却在fragment_container的后面——解析到fragment_container这一行时,系统还没加载到adView,自然找不到这个id资源,就抛出了报错。
两种解决方案
方案1:调整控件声明顺序(推荐)
把AdView的代码移到fragment_container的前面,这样系统解析到fragment_container的layout_above属性时,adView的id已经被注册好了:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:gravity="center" android:background="@drawable/bg_lock" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" app:popupTheme="@style/ThemeOverlay.AppCompat.Light" android:elevation="4dp" /> <!-- 把AdView移到fragment_container前面 --> <com.google.android.gms.ads.AdView xmlns:ads="http://schemas.android.com/apk/res-auto" android:id="@+id/adView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" ads:adSize="BANNER" ads:adUnitId="@string/addUnit" /> <FrameLayout android:layout_below="@id/toolbar" android:id="@+id/fragment_container" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_above="@id/adView" android:layout_marginBottom="5dp"/> </RelativeLayout>
方案2:提前声明id(仅作备选)
如果不想调整控件顺序,可以把fragment_container里的@id/adView改成@+id/adView——这相当于先创建这个id,后面的AdView再复用该id。不过这种方式会让布局结构的可读性下降,所以优先推荐方案1。
修改后这一行代码会变成:
android:layout_above="@+id/adView"
验证效果
两种方案都能解决报错问题,用方案1能让布局的依赖关系更清晰,也更符合Android布局解析的逻辑。
内容的提问来源于stack exchange,提问作者Muhammad Junaid Khalid
相关产品推荐
相关产品推荐

