Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Tải ảnh với Glide trong Android

Glide là thư viện tải và hiển thị ảnh mạnh mẽ, phổ biến nhất Android hiện nay (phát triển bởi Bumptech, được Google khuyến nghị). Hỗ trợ tải từ URL, file, resource, caching thông minh, transformation, animation, GIF, WebP...

Tích hợp Glide

Bước 1: Thêm dependency vào build.gradle (Module: app)

dependencies {
    // Glide core
    implementation 'com.github.bumptech.glide:glide:4.16.0'
    // Annotation processor (bắt buộc cho GeneratedAPI)
    annotationProcessor 'com.github.bumptech.glide:compiler:4.16.0'
    // Hoặc cho Kotlin
    // kapt 'com.github.bumptech.glide:compiler:4.16.0'
}

Bước 2: Layout activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="300dp"
        android:layout_height="300dp"
        android:scaleType="centerCrop"
        android:contentDescription="Ảnh từ Glide"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Bước 3: MainActivity.java - Tải ảnh cơ bản

import android.os.Bundle;
import android.widget.ImageView;
import androidx.appcompat.app.AppCompatActivity;
import com.bumptech.glide.Glide;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ImageView imageView = findViewById(R.id.imageView);
        
        // Tải ảnh từ URL đơn giản nhất
        Glide.with(this)
             .load("https://www.tutorialspoint.com/images/tp-logo-diamond.png")
             .into(imageView);
    }
}

Các tùy chọn nâng cao

Placeholder & Error handling

Glide.with(this)
    .load(url)
    .placeholder(R.drawable.placeholder)      // Ảnh chờ tải
    .error(R.drawable.error_image)            // Ảnh khi lỗi
    .fallback(R.drawable.fallback)            // Ảnh khi URL null/empty
    .into(imageView);

Resize & Transformation

Glide.with(this)
    .load(url)
    .override(800, 600)                       // Resize trước khi load (tối ưu memory)
    .centerCrop()                             // Crop giữa
    // .fitCenter()                          // Fit toàn bộ ảnh
    // .circleCrop()                         // Crop tròn
    .transform(new RoundedCorners(16))        // Bo góc (cần dependency transformation)
    .into(imageView);

Caching Strategy

// Chỉ load từ cache (offline)
Glide.with(this)
    .load(url)
    .onlyRetrieveFromCache(true)
    .into(imageView);

// Skip memory cache
Glide.with(this)
    .load(url)
    .skipMemoryCache(true)
    .into(imageView);

// Disk cache strategy
.diskCacheStrategy(DiskCacheStrategy.ALL)     // Cache cả original và transformed
// .diskCacheStrategy(DiskCacheStrategy.NONE) // Không cache disk
// .diskCacheStrategy(DiskCacheStrategy.DATA) // Chỉ cache original
// .diskCacheStrategy(DiskCacheStrategy.RESOURCE) // Chỉ cache transformed

Listener & Callback

Glide.with(this)
    .load(url)
    .listener(new RequestListener() {
        @Override
        public boolean onLoadFailed(@Nullable GlideException e, Object model, 
                                    Target target, boolean isFirstResource) {
            // Xử lý lỗi
            return false; // false = cho Glide xử lý error placeholder
        }

        @Override
        public boolean onResourceReady(Drawable resource, Object model, 
                                       Target target, DataSource dataSource, boolean isFirstResource) {
            // Tải thành công
            return false;
        }
    })
    .into(imageView);

Tải ảnh vào Notification / Widget (AppWidget)

// Sử dụng submit() thay vì into() cho target tùy chỉnh
Glide.with(context)
    .asBitmap()
    .load(url)
    .submit(notificationWidth, notificationHeight)
    .get(); // Blocking - chỉ dùng cho background thread

So sánh Glide vs Picasso vs Coil

Đặc điểmGlidePicassoCoil (Kotlin)
Hiệu suấtRất tốtTốtRất tốt (coroutines)
GIF/AnimationHỗ trợ tốtHạn chếHỗ trợ tốt
APIFluent, phức tạpĐơn giảnKotlin-first, coroutines
Kích thước~480KB~120KB~300KB
Lifecycle awarenessTự động (RequestManager)ManualTự động (lifecycleScope)

Chạy ứng dụng

Build và chạy. ImageView sẽ hiển thị logo Tutorialspoint tải từ internet. Glide tự động xử lý caching, lifecycle, placeholder.

Lưu ý quan trọng

  • Cần thêm quyền INTERNET trong AndroidManifest.xml
  • Glide tự động huỷ request khi Activity/Fragment destroyed (tránh leak)
  • Dùng .override(width, height) để tránh OOM với ảnh lớn
  • Cho danh sách (RecyclerView): Glide tự handle recycle view đúng cách