You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android开发求助:ImageView无法显示drawable目录下的图片

解决ImageView无法显示drawable图片的问题

我看了你的布局代码,一眼就发现问题所在啦!你用了tools:srcCompat="@drawable/nature"这个属性,但它只是给Android Studio预览界面用的——实际运行APP时,系统根本不会加载这张图片,这就是你看不到图片的核心原因。

修复超简单,只要改一个属性:

把仅用于预览的tools:srcCompat,替换成真正能让APP加载图片的android:src或者app:srcCompat(更推荐后者,它对矢量图和低版本Android兼容更好)

修改后的完整布局代码如下:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/constrainLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:scaleType="centerInside"
        android:visibility="visible"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.485"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:ignore="ContentDescription"
        app:srcCompat="@drawable/nature"/> <!-- 这里替换为实际生效的图片属性 -->
</androidx.constraintlayout.widget.ConstraintLayout>

额外小提醒:

  • 确认drawable目录下真的存在nature图片文件哦,Android资源文件名是区分大小写的,别写错名字
  • 如果用的是矢量图,使用app:srcCompat需要在Module级别的build.gradle里加一行配置:
android {
    defaultConfig {
        vectorDrawables.useSupportLibrary = true
    }
}

改完之后重新运行APP,就能正常看到图片啦!

内容的提问来源于stack exchange,提问作者Ubaid Khan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 09:02:45