为什么我的 ImageView 不显示图像?

Why is my ImageView not showing the image?

正在尝试使用 ImageView 显示图像,但未显示。 源图像保存在 drawable 目录中。

<?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"
        tools:srcCompat="@drawable/nature"/>
</androidx.constraintlayout.widget.ConstraintLayout>

而不是使用

        tools:srcCompat="@drawable/nature"

使用

        android:src="@drawable/nature"

tools:srcCompat="@drawable/nature" 用于在设计时显示图像。当你需要在 运行 时间看到它时,你应该在你的 ImageView 中添加 android:src="@drawable/nature" 如下:

<?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"
        android:src="@drawable/nature"
        tools:ignore="ContentDescription"
        tools:srcCompat="@drawable/nature"/>
</androidx.constraintlayout.widget.ConstraintLayout>

只需更换

tools:srcCompat="@drawable/nature"

来自

android:src="@drawable/nature"