Android应用添加图片遇FrameLayout问题及ImageView资源引用报错求助
解决ImageView资源引用错误与FrameLayout布局问题
嘿,我看你在AIDE开发Android应用时遇到了两个头疼的问题,咱们一步步来解决:
首先是那个No resource found that matches the given name的错误,原因很明确——你把图片放在了drawable/android这个子文件夹里,但Android的资源系统根本不识别drawable目录下的自定义子文件夹!你写的@drawable/android是在找名为android的资源文件,而不是找android文件夹里的图片,所以系统肯定找不到。
修复资源引用错误:
- 最简单的办法:把你的
a.jpeg直接移动到res/drawable的根目录下(也就是去掉android子文件夹),然后把ImageView的android:src改成@drawable/a就行 - 如果你想给图片分类,别用drawable的子文件夹,要么重命名图片(比如叫
android_logo.jpeg,引用@drawable/android_logo),要么用assets目录存图片(不过这个得用代码加载,没法直接在XML里引用)
然后是FrameLayout的问题,看你的布局代码,有两个明显的问题:
- FrameLayout里重复写了
xmlns:android这些命名空间,根布局LinearLayout已经声明过了,子布局完全不需要重复写 - FrameLayout的
android:layout_height="match_parent"会让它占满整个屏幕,直接把上面的TextView和Button都挤得看不见了!
修复FrameLayout布局:
- 删掉FrameLayout里的
xmlns:android、xmlns:app、xmlns:tools这三行,完全没用 - 调整FrameLayout的高度,比如用
layout_weight让它和上面的控件合理分配空间(我在下面的代码里给它设了layout_height="0dp"和layout_weight="1",这样它会占满LinearLayout剩下的所有空间) - 另外,你在LinearLayout里的TextView加了
android:layout_centerVertical="true"和android:layout_centerHorizontal="true",这些是RelativeLayout的属性,在LinearLayout里根本不生效,赶紧删掉这些无效代码
下面是修复后的完整布局代码,我还顺便把字体大小的dp改成了sp(这是Android开发的最佳实践,适配系统字体缩放):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#fff000" android:gravity="center_horizontal" android:orientation="vertical"> <TextView android:id="@+id/tw2" android:textSize="30sp" android:layout_margin="16dp" android:text="Güzel Sözler" android:shadowColor="#00ccff" android:shadowRadius="2" android:shadowDx="1" android:shadowDy="1" android:textIsSelectable="true" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/tw1" android:textSize="15sp" android:layout_margin="16dp" android:text="" android:shadowColor="#00ccff" android:shadowRadius="2" android:shadowDx="1" android:shadowDy="1" android:textIsSelectable="true" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:id="@+id/btn1" android:text="random" android:textSize="20sp" android:background="#cae1ff" android:textColor="#ff3030" android:layout_gravity="bottom" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <FrameLayout android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1"> <ImageView android:layout_width="match_parent" android:layout_height="match_parent" android:scaleType="fitXY" android:src="@drawable/a" /> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginBottom="20dp" android:gravity="center_horizontal|bottom" android:text="Android Programlama" android:textColor="#ffffff" android:textSize="30sp" android:textStyle="bold"/> </FrameLayout> </LinearLayout>
最后再提个小建议:如果你的图片是应用图标类的,建议放在res/mipmap目录下,而不是drawable,这样系统会根据不同分辨率自动适配~
内容的提问来源于stack exchange,提问作者eqwe delly
相关产品推荐
相关产品推荐

