[Android] A simple case of using Glide to load images into ImageView

Preface

Android Glide is a popular open source library for loading and displaying images in Android apps. It provides a simple and easy-to-use API that can help developers efficiently load remote images, local images, and GIF animations, and provides functions such as caching and memory management to make image loading in mobile applications smoother and more efficient. Glide also supports many advanced functions, such as dynamic image resizing, rounded images, blurred images, etc., so it is widely used in the development of Android applications.


Steps

  1. Add permissions to AndroidManifest.xml manifest file

Here is a snippet of a sample AndroidManifest.xml file showing the location of the <uses-permission> tag:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapp">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        ...>
        ...
    </application>
</manifest>

Be sure to place the <uses-permission> tag outside the <application> tag, but within the <application> tag. This ensures that permission declarations take effect within the scope of the application, rather than just within an activity or service.

  1. Add dependent libraries

Add the following dependencies in the section of thebuild.gradle.kts file:dependencies

    implementation ("com.github.bumptech.glide:glide:4.12.0")

CompletedependenciesPartial example:

dependencies {
    
    
    implementation ("com.github.bumptech.glide:glide:4.12.0")
    implementation("androidx.appcompat:appcompat:1.6.1")
    implementation("com.google.android.material:material:1.8.0")
    implementation("androidx.constraintlayout:constraintlayout:2.1.4")
    testImplementation("junit:junit:4.13.2")
    androidTestImplementation("androidx.test.ext:junit:1.1.5")
    androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1")
}
  1. Sync Gradle

After adding dependent libraries, remember to click the "Sync Project with Gradle Files" button in the Android Studio toolbar to ensure that Gradle files are synchronized.

  1. Write code to load images using Glide
Uri uri = Uri.parse("这里填图像链接");

Glide.with(ArchiveActivity.this)
        .load(uri)
        .placeholder(R.drawable.baseline_photo_240)
        .error(R.drawable.baseline_warning_240)
        .into(ivAvatar);
  1. Image successfully loaded into ImageView


References

https://blog.csdn.net/g984160547/article/details/119991748

Guess you like

Origin blog.csdn.net/qq_34988204/article/details/135000494