如何将图像放入 Android Studio For Android Noutgat 及以下版本的图像视图中

How can I put image in Image View in Android Studio For Android Noutgat and below

我的项目有图像视图。它无法工作 Android Noutgat 及以下版本。但它可以用于 Android 8.0 及更高版本。我该如何解决。

MyActivity.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="MainActivity"
    android:background="@color/Color_white"
    >
    
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="300dp"
        android:layout_alignParentBottom="true"
        android:background="@drawable/backroundlegend"
        />
</RelativeLayout>

当我删除 imageView 时,它可以用于 Android Noutgat 及以下版本

Android 版本与您的情况无关。

当您将图像设置为 ImageView 时,您需要像 Picasso, Glide, Fresco, Coil 等图像加载程序库以编程方式加载图像,如果您不这样设置图像,则图像是以非常低的质量或大部分时间显示,图像不会加载。您可以使用任何一种,但我认为 Glide 是最受欢迎的。

您要做的是给 ImageView 一个 ID,在与此布局关联的 Java/Kotlin class 文件中访问它,并使用任何设置图像到它这些图书馆。

但首先,您必须在您的项目中实施该库。请参阅我在上面链接的这些库页面上的实施说明。

然后,将IDimageView设为

<ImageView
    android:id="@+id/imageView"
    ...
    />

然后,在Java/Kotlin文件中访问

//Kotlin
val imageView = findViewById(R.id.imageView)
//Java
ImageView imageView = findViewById(R.id.imageView);

然后,将您的图像设置为

//this is the Context here for activity, use context or requireContext() in Fragment.
Glide.with(this).load(R.drawable.backgroundlegend).into(imageView)

在此之后,您的图像将会出现。请记住这一点,当您设置 svg 和 drawables 时,您不需要以编程方式加载图像,但是当您使用 png,jpg/jpeg 等图像时,您必须使用图像加载器。此外,您可以使用 ImageViewscaleType 属性 来调整 ImageView 的视图范围内的图像。