About the Glide

Glide is a fast and efficient Android image loading library that focuses on smooth scrolling. Glide provides an easy-to-use API, a high-performance, scalable decode pipeline, and automated resource pooling technology.

Glide supports pulling, decoding, and displaying video snapshots, pictures, and GIF animations. Glide’s Api is so flexible that developers can plug in and replace it with any network stack they like. Glide by default uses a customized HttpurlConnection-based stack, but it also provides a tool library for quick integration with Google Volley and Square OkHttp.

Although Glide’s primary goal is to make scrolling through any kind of list of images as fast and smooth as possible, Glide can actually do almost anything you need to pull/zoom/display remote images.

Glide configuration

If you use Gradle, you can add a dependency on Glide from Maven Central or JCenter. Also, you need to add Android support library dependencies.

Dependencies {the compile 'com. Making. Bumptech. Glide: glide: 4.3.1' annotationProcessor 'com. Making. Bumptech. Glide: the compiler: 4.3.1'} repositories {mavenCentral () maven {url 'https://maven.google.com'}}Copy the code

Add permissions

Glide assumes that the data you want to access is stored in your application and does not require any permissions. That is, most applications load images from the device (DCIM, gallery, or elsewhere on the SD card) or from the Internet. Therefore, you may need to include one or more of the permissions listed below, depending on your application scenario.

Internet

If you plan to load data from a URL or a network connection, you need to add INTERNET and ACCESS_NETWORK_STATE permissions to your Androidmanifest.xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="your.package.name" <uses-permission android:name="android.permission.INTERNET"/> <! -- Allows Glide to monitor connectivity status and restart failed requests if users go from a a disconnected to a connected network state. --> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <application> ...  </application> </manifest>Copy the code

ACCESS_NETWORK_STATE is not technically necessary for Glide to load urls, but it will help Glide handle Flaky networks and flight patterns. Continue to read the connection monitoring section below for details.

Connectivity Monitoring

Glide automatically helps you with patchy network connections if you are loading images from urls: It listens for the user’s connection status and restarts requests that failed before the user reconnects to the network. If Glide detects that your application has ACCESS_NETWORK_STATUS, Glide will automatically listen for connection status without additional changes.

You can verify that Glide is listening to network state by checking the ConnectivityMonitor log tag:

adb shell setprop log.tag.ConnectivityMonitor DEBUG

Copy the code

If you successfully added the ACCESS_NETWORK_STATUS permission, you will see a log in logcat that looks something like this:

11 to 18 18:51:23. 673 D/ConnectivityMonitor (16236) : ACCESS_NETWORK_STATE permission granted, Registering connectivity monitor 11-18 18:48:55.135 V/ConnectivityMonitor(15773): Connectivity changed: False 11-18 18:49:00.701 V/ConnectivityMonitor(15773): Connectivity changed: trueCopy the code

If the permission is missing, you will see an error:

11 to 18 18:51:23. 673 D/ConnectivityMonitor (16236) : ACCESS_NETWORK_STATE permission missing, cannot register connectivity monitorCopy the code
Local Storage

To load images from a local folder or DCIM or gallery, you will need to add the READ_EXTERNAL_STORAGE permission:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="your.package.name"

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <application>
      ...
    </application>
</manifest>
Copy the code

And if you want to use ExternalPreferredCacheDiskCacheFactory to Glide cache storage to the public on the SD card, you will need to add WRITE_EXTERNAL_STORAGE permission to:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="your.package.name"

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application>
      ...
    </application>
</manifest>
Copy the code
Proguard(code obfuscation)

If you use ProGuard, add the following code to your proGuard.cfg file:

-keep public class * implements com.bumptech.glide.module.GlideModule
-keep public class * extends com.bumptech.glide.module.AppGlideModule
-keep public enum com.bumptech.glide.load.resource.bitmap.ImageHeaderParser$** {
    **[] $VALUES;
    public *;
}
Copy the code

Basic usage

In most cases, loading an image using Glide is very simple, one line of code is enough:

Glide. With (fragment)// Fragment. Load (myUrl)// network request to load image address. //imageViewCopy the code

Unloading is also simple:

Glide.with(fragment).clear(imageView);

Copy the code

While it’s a good practice to cancel unnecessary loads in a timely manner, it’s not necessary. In fact, When an Activity or Fragment instance passed in [Glide. With ()] is destroyed, Glide automatically unloads and reclaims the resource.

Use in the Application module

In the Application module, you can create a class with the @glidemodule annotation inherited from AppGlideModule. This class generates a streaming API with inline options and custom options in the integration library:

package com.example.myapp;

import com.bumptech.glide.annotation.GlideModule;
import com.bumptech.glide.module.AppGlideModule;

@GlideModule
public final class MyAppGlideModule extends AppGlideModule {}

Copy the code

The default generated API name is GlideApp, the same as the package name of the subclass [AppGlideModule]. Replace Glide. With () with glideapp.with () in the Application module to use the API for loading.

GlideApp.with(fragment)
   .load(myUrl)
   .placeholder(placeholder)
   .fitCenter()
   .into(imageView);

Copy the code
Use in ListView and RecyclerView

The code for loading images in ListView or RecyclerView is exactly the same as loading images in a separate View. Glide already handles View reuse and request cancellation automatically:

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    String url = urls.get(position);
    Glide.with(fragment)
        .load(url)
        .into(holder.imageView);
}

Copy the code

It is not necessary to null the URL. If the URL is null, Glide will empty the View content or display placeholder Drawable or fallback Drawable content.

Glide’s only requirement is that for any reusable View or [Target] that has been loaded with Glide in the previous location, a new load operation is performed in the new location or a call to the [clear()] API to stop Glide.

@Override public void onBindViewHolder(ViewHolder holder, int position) { if (isImagePosition(position)) { String url = urls.get(position); Glide.with(fragment) .load(url) .into(holder.imageView); } else { Glide.with(fragment).clear(holder.imageView); holder.imageView.setImageDrawable(specialDrawable); }}Copy the code

Calling [clear()] or into(View) on the View indicates that the previous load operation is canceled, and that Glide does not change the View’s contents after the method call is complete. If you forget to call [clear()] and do not start a new load operation, you may have a Drawable set for a view that used Glide to load the image in its previous position. Glide may change the view back to its original content after it is loaded.

The code here uses RecyclerView as an example, but the same rules apply to ListView.

The View target

In addition to loading bitmaps and Drawable into a View, you can also start loading them asynchronously into your custom Target:

Glide.with(context
  .load(url)
  .into(new SimpleTarget<Drawable>() {
    @Override
    public void onResourceReady(Drawable resource, Transition<Drawable> transition) {
      // Do something with the Drawable here.
    }
  });

Copy the code
A background thread

[submit(int, int)];

FutureTarget<Bitmap> futureTarget =
  Glide.with(context)
    .asBitmap()
    .load(url)
    .submit(width, height);

Bitmap bitmap = futureTarget.get();

// Do something with the Bitmap and then when you're done with it:
Glide.with(context).clear(futureTarget);

Copy the code

If you don’t want the Bitmap and Drawable to be in the background thread itself, you can also start asynchronous loading in the same way as the foreground thread:

Glide.with(context)
  .asBitmap()
  .load(url)
  .into(new Target<Bitmap>() {
    ...
  });
Copy the code

A placeholder

Glide allows users to specify three different types of placeholders for use in three different scenarios:

  • placeholder
  • error
  • fallback
Placeholders (Placeholder)

Placeholders are the Drawable that is displayed while the request is being executed. When the request completes successfully, the placeholder is replaced by the requested resource. If the requested resource is loaded from memory, the placeholder may not be displayed at all. If the request fails and the error Drawable is not set, the placeholder is continuously displayed. Similarly, if the requested URL/Model is null, and neither error Drawable nor fallback is set, the placeholder will continue to be displayed.

Using the generated API:

GlideApp.with(fragment)
  .load(url)
  .placeholder(R.drawable.placeholder)
  .into(view);

Copy the code

Or:

GlideApp.with(fragment)
  .load(url)
  .placeholder(new ColorDrawable(Color.BLACK))
  .into(view);
Copy the code
Is an Error (Error)

Error Drawable is displayed when the request fails permanently. Error Drawable is also displayed when the requested URL /model is null and a fallback Drawable is not set.

With the generated API:

GlideApp.with(fragment)
  .load(url)
  .error(R.drawable.error)
  .into(view);

Copy the code

Or:

GlideApp.with(fragment)
  .load(url)
  .error(new ColorDrawable(Color.RED))
  .into(view);

Copy the code
Fallback

Fallback Drawable is displayed when the requested URL /model is null. The primary purpose of a Fallback Drawable is to allow the user to indicate whether NULL is an acceptable normal condition. For example, a null profile URL might imply that the user has no profile picture set and should therefore use the default profile picture. However, NULL can also indicate that the metadata is not valid at all, or is not reachable. Glide handles NULL as an error by default, so applications that accept NULL should explicitly set a fallback Drawable.

Using the generated API:

GlideApp.with(fragment)
  .load(url)
  .fallback(R.drawable.fallback)
  .into(view);

Copy the code

Or:

GlideApp.with(fragment)
  .load(url)
  .fallback(new ColorDrawable(Color.GREY))
  .into(view);
Copy the code

options

Request options

Most of the Settings in Glide can be applied to programs through the RequestOptions class and the Apply () method.

Using Request Options, you can implement (including but not limited to) :

  • Placeholders (Placeholders)
  • Conversion (Transformations)
  • Cache policy (Caching Strategies)
  • Component-specific setting items, such as encoding quality, orBitmapDecoding configuration, etc.

For example, to apply a CenterCrop transformation, you could use the following code:

import static com.bumptech.glide.request.RequestOptions.centerCropTransform;

Glide.with(fragment)
    .load(url)
    .apply(centerCropTransform(context))
    .into(imageView);

Copy the code

In this example, static imports of methods in the RequestOptions class are used, which makes the code look cleaner and smoother.

If you want different parts of your application to share the same load options, you can also initialize a new RequestOptions object and pass it in each time it loads:

RequestOptions cropOptions = new RequestOptions().centerCrop(context); . Glide.with(fragment) .load(url) .apply(cropOptions) .into(imageView);Copy the code

The apply() method can be called multiple times, so RequestOption can be used in combination. If there are conflicting Settings between RequestOptions objects, only the last RequestOptions applied will take effect.

Generated API

If you are using the Generated API, all request option methods are inlined and can be used directly:

GlideApp.with(fragment)
    .load(url)
    .centerCrop()
    .into(imageView);

Copy the code
Transition option

TransitionOptions is used to determine what happens when your load is complete.

The following transformations can be applied with TransitionOption:

  • The View fade in
  • Cross fades in with placeholders
  • Or nothing at all

If you don’t use transformations, your image will “jump” into its display position, replacing the previous image. To avoid this sudden change, you can fade in the view or have multiple drawables cross fade in, using TransitionOptions.

For example, to apply a cross fade transform:

import static com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions.withCrossFade;

Glide.with(fragment)
    .load(url)
    .transition(withCrossFade())
    .into(view);

Copy the code

Unlike RequestOptions, TransitionOptions are unique to a particular resource type, and the transitions you can use depend on what type of resource you want Glide to load.

As a result, if you request to load a Bitmap, you need to use BitmapTransitionOptions, rather than DrawableTransitionOptions. Similarly, when you request to load a Bitmap, you only need to do simple fade-ins instead of complex cross-fade-ins.

RequestBuilder

The RequestBuilder is the skeleton of a request in Glide that takes the requested URL and your setup items to start a new load process.

Using RequestBuilder you can specify:

  • The type of resource you want to load (Bitmap, Drawable, or whatever)
  • The address of the resource you want to load (URL /model)
  • The View you want to eventually load into
  • Anything you want to apply (one or more)RequestOptionobject
  • Anything you want to apply (one or more)TransitionOptionobject
  • Any thumbnail you want to load ()

You can construct a RequestBuilder object by calling Glide. With () and then use one of the AS methods:

RequestBuilder<Drawable> requestBuilder = Glide.with(fragment).asDrawable();

Copy the code

Or use Glide. With () then load() :

RequestBuilder<Drawable> requestBuilder = Glide.with(fragment).load(url);

Copy the code
Selecting a Resource Type

RequestBuilders are specific to the type of resource they are going to load. By default you will get a Drawable RequestBuilder, but you can use as… A series of methods to change the request type. For example, if you call asBitmap(), you will get a Bitmap RequestBuilder object instead of the default Drawable RequestBuilder.

RequestBuilder<Bitmap> requestBuilder = Glide.with(fragment).asBitmap();

Copy the code
Application RequestOptions

As mentioned earlier, you can apply RequestOptions using the apply() method and TransitionOptions using the Transition () method.

RequestBuilder<Drawable> requestBuilder = Glide.with(fragment).asDrawable();
requestBuilder.apply(requestOptions);
requestBuilder.transition(transitionOptions);

Copy the code

RequestBuilder can also be reused to start multiple requests:

RequestBuilder<Drawable> requestBuilder =
        Glide.with(fragment)
            .asDrawable()
            .apply(requestOptions);

for (int i = 0; i < numViews; i++) {
   ImageView view = viewGroup.getChildAt(i);
   String url = urls.get(i);
   requestBuilder.load(url).into(view);
}

Copy the code
Thumbnail requests

Glide’s Thumbnail API allows you to specify a RequestBuilder to launch in parallel with your main request. Thumbnails are displayed during the main request load. If the main request completes before the thumbnail request, the image in the thumbnail request will not be displayed. The [Thumbnail] API allows you to easily and quickly load a low resolution version of the image while loading a lossless version of the image at the same time, which reduces the amount of time users spend staring at load indicators.

The Thumbnail () API works for both local and remote images, especially if low-resolution thumbnails are stored in Glide’s disk cache, they will load quickly.

The Thumbnail API is relatively simple to use:

Glide.with(fragment)
  .load(url)
  .thumbnail(Glide.with(fragment)
    .load(thumbnailUrl))
  .into(imageView);

Copy the code

As long as your thumbnailUrl points to an image at a lower resolution than your main url, it will work fine. There are a number of loading apis that provide different ways to specify image sizes, and they are particularly useful for thumbnail apis.

If you only want to load a local image, or if you only have a separate remote URL, you can still benefit from the thumbnail API. Please use Glide’s Override or sizeMultiplier API to force Glide to load a low resolution image in the thumbnail request:

int thumbnailSize = ... ; Glide.with(fragment) .load(localUri) .thumbnail(Glide.with(fragment) .load(localUri) .override(thumbnailSize)) .into(view);Copy the code

There is a simplified version of the Thumbnail method that requires only a single sizeMultiplier parameter. This is especially useful if you just want to load the same image for your image, but with a percentage size of View or Target:

Glide. With (fragment).load(localUri). Thumbnail (/*sizeMultiplier=*/ 0.25f). Into (imageView);Copy the code
Start a new request on failure

Starting with Glide 4.3.0, you can now specify a RequestBuilder using the Error API to start a new load if the main request fails. For example, loading a fallbackUrl after a primaryUrl request fails:

Glide.with(fragment)
  .load(primaryUrl)
  .error(Glide.with(fragment)
      .load(fallbackUrl))
  .into(imageView);

Copy the code

If the main request completes successfully, the Error RequestBuilder will not be started. If you specify both a thumbnail and an Error RequestBuilder, the backup RequestBuilder will start if the main request fails, even if the thumbnail request succeeds.

Component options

The Option class is a generic way to add parameters to Glide’s components, including ModelLoaders, ResourceDecoders, ResourceEncoders, Encoders, and so on. Some Glide’s built-in components provide Settings, and custom components can add Settings.

Option is applied to the request through the RequestOptions class:

import static com.bumptech.glide.request.RequestOptions.option;

Glide.with(context)
  .load(url)
  .apply(option(MyCustomModelLoader.TIMEOUT_MS, 1000L))
  .into(imageView);

Copy the code

You can also create a new RequestOptions object:

RequestOptions options = new RequestOptions()
  .set(MyCustomModelLoader.TIMEOUT_MS, 1000L);

Glide.with(context)
  .load(url)
  .apply(options)
  .into(imageView);

Copy the code

Or use the Generated API:

GlideApp.with(context)
  .load(url)
  .set(MyCustomModelLoader.TIMEOUT_MS, 1000L)
  .into(imageView);
Copy the code

transform

In Glide, you can take a resource, make changes to it, and then return to the modified resource. The transform operation is usually used to complete clipping or apply filters to bitmaps, but it can also be used to convert GIFs or even custom resource types.

Built-in types

Glide provides a number of built-in transformations, including:

  • CenterCrop
  • FitCenter
  • CircleCrop
The default transformation
RequestOptions options = new RequestOptions();
options.centerCrop();

Glide.with(fragment)
    .load(url)
    .apply(options)
    .into(imageView);

Copy the code

Most of the built-in transformations have static imports for API smoothness. For example, you can apply a FitCenter transform statically:

import static com.bumptech.glide.request.RequestOptions.fitCenterTransform;

Glide.with(fragment)
    .load(url)
    .apply(fitCenterTransform())
    .into(imageView);

Copy the code

If you are using the Generated API, these transform methods are already inline, so they are even easier to use:

GlideApp.with(fragment)
  .load(url)
  .fitCenter()
  .into(imageView);
Copy the code
multi

By default, each transform() call, or any call to a specific transform method (fitCenter(), centerCrop(), bitmapTransform() etc), replaces the previous transform.

If you want to apply multiple transformations in a single load, use the MultiTransformation class.

Using the generated API:

Glide.with(fragment)
  .load(url)
  .transform(new MultiTransformation(new FitCenter(), new YourCustomTransformation())
  .into(imageView);

Copy the code

Or use a combination of shortcuts and the GENERATED API:

GlideApp.with(fragment)
  .load(url)
  .transforms(new FitCenter(), new YourCustomTransformation())
  .into(imageView);

Copy the code

Note that the order in which you pass the transformation parameters to the constructor of MultiTransformation determines the order in which these transformations are applied.

Custom transformation

Although Glide provides a variety of built-in Transformations implementations, you can also implement your own if you need additional functionality.

BitmapTransformation

If you only need to transform bitmaps, it’s best to start by inheriting BitmapTransformation. BitmapTransformation handles some basics, including extracting and reclaiming the original Bitmap if your transformation returns a newly modified Bitmap.

A simple implementation might look like this:

public class FillSpace extends BitmapTransformation {
    private static final String ID = "com.bumptech.glide.transformations.FillSpace";
    private static final String ID_BYTES = ID.getBytes(STRING_CHARSET_NAME);

    {@literal @Override}
    public Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
        if (toTransform.getWidth() == outWidth && toTransform.getHeight() == outHeight) {
            return toTransform;
        }

        return Bitmap.createScaledBitmap(toTransform, outWidth, outHeight, /*filter=*/ true);
    }

    {@literal @Override}
    public void equals(Object o) {
      return o instanceof FillSpace;
    }

    {@literal @Override}
    public int hashCode() {
      return ID.hashCode();
    }

    {@literal @Override}
    public void updateDiskCacheKey(MessageDigest messageDigest)
        throws UnsupportedEncodingException {
      messageDigest.update(ID_BYTES);
    }
}

Copy the code

While your Transformation will almost certainly be more complex than this example, it should contain the same basic elements and carbon copy methods.

Required methods

Note in particular that for any Transformation subclass, including BitmapTransformation, you have three methods that you must implement to make disk and memory caches work correctly:

    1. equals()
    1. hashCode()
    1. updateDiskCacheKey

If your Transformation has no arguments, it usually uses a static final String containing the qualified name of the full package as an ID, which can form the basis of hashCode(), And can be used to update MessageDigest passed in to updateDiskCacheKey(). If your Transformation requires parameters and it affects how the Bitmap is transformed, they must also be included in these three methods.

For example, Glide’s round corners transform accepts an int that determines the radian of the RoundedCorners. Its equals(), hashCode(), and updateDiskCacheKey implementations look like this:

  @Override
  public boolean equals(Object o) {
    if (o instanceof RoundedCorners) {
      RoundedCorners other = (RoundedCorners) o;
      return roundingRadius == other.roundingRadius;
    }
    return false;
  }

  @Override
  public int hashCode() {
    return Util.hashCode(ID.hashCode(),
        Util.hashCode(roundingRadius));
  }

  @Override
  public void updateDiskCacheKey(MessageDigest messageDigest) {
    messageDigest.update(ID_BYTES);

    byte[] radiusData = ByteBuffer.allocate(4).putInt(roundingRadius).array();
    messageDigest.update(radiusData);
  }

Copy the code

The original String is still there, but roundingRadius is incorporated into the three methods. Here, the updateDiskCacheKey method also demonstrates how you can use ByteBuffer to include basic parameters in your updateDiskCacheKey implementation.

Don’t forget equals()/hashCode()

It’s worth reiterating whether you need to implement equals() and hashCode() methods in order for the memory cache to work properly. Unfortunately, BitmapTransformation and Transformation will compile even if you don’t copy them, but that doesn’t mean they will work.

The cache in Glide

By default, Glide checks the following levels of cache before starting a new image request:

    1. Active Resources – Is there another View showing this image right now?
    1. Memory cache – Has the image been loaded recently and still exists in Memory?
    1. Resource Type – Has this image been decoded, converted, and written to disk cache before?
    1. Data Source – Was the resource used to build this image previously written to the file cache?

The first two steps check if the image is in memory, and if so, return the image directly. The last two steps check that the picture is on disk so that it can be returned quickly but asynchronously.

If all four steps fail to find the image, Glide returns to the original resource to retrieve the data (original file, Uri, Url, etc.).

Cache Keys

In Glide V4, all cache keys contain at least two elements:

  1. Requested load model (File, Url, Url)
  2. An optional Signature

In addition, the cache keys for steps 1-3(Active Resource, memory cache, Resource disk cache) also contain some additional data, including:

  1. Width and height
  2. optionalTransformation
  3. Any additional Options added
  4. The data type requested (Bitmap, GIF, or other)

The active resource and memory caches also use slightly different keys than the disk resource caches to accommodate memory Options, such as Options that affect the Bitmap configuration or other parameters that are only used when decoding.

To generate the cache key name on the disk cache, each of the above elements is hashed to create a separate string key name, which is then used as the file name on the disk cache.

Configure the cache

Glide provides a series of options that allow you to choose how the load request interacts with the Glide cache.

Disk Caching policy

DiskCacheStrategy can be applied to each individual request by the DiskCacheStrategy method. Currently supported policies allow you to prevent the loading process from using or writing to disk cache, optionally caching only unmodified native data, or only altered thumbnails, or both.

The default policy is called AUTOMATIC, and it tries to use the best policy for local and remote images. When you load remote data (for example, downloaded from a URL), AUTOMATIC only stores raw data that has not been modified (for example, transformed, clipped) by your loading process, because downloading remote data is much more expensive than adjusting data that already exists on disk. For local data, AUTOMATIC stores only the thumbnails that have been transformed, because it’s easy to retrieve the original data even if you need to generate another image of a different size or type.

Specifying DiskCacheStrategy is very easy:

GlideApp.with(fragment)
  .load(url)
  .diskCacheStrategy(DiskCacheStrategy.ALL)
  .into(imageView);

Copy the code
Load images only from cache

In some cases, you may want the load to fail as long as the image is not in the cache (such as traffic saving mode). To accomplish this, you can use the onlyRetrieveFromCache method on a single request basis:

GlideApp.with(fragment)
  .load(url)
  .onlyRetrieveFromCache(true)
  .into(imageView);

Copy the code

If the image is in memory cache or disk cache, it will be displayed. Otherwise, as long as this option is set to true, the load will be considered a failure.

Skip the cache

Glide also provides some alternatives if you want to ensure that a particular request skips disk and/or memory caches (for example, image captcha).

Skip only memory cache, use skipMemoryCache() :

GlideApp.with(fragment)
  .load(url)
  .skipMemoryCache(true)
  .into(view);

Copy the code

To skip only disk caching, use diskCacheStrategy.none:

GlideApp.with(fragment)
  .load(url)
  .diskCacheStrategy(DiskCacheStrategy.NONE)
  .into(view);

Copy the code

These two options can be used together:

GlideApp.with(fragment)
  .load(url)
  .diskCacheStrategy(DiskCacheStrategy.NONE)
  .skipMemoryCache(true)
  .into(view);

Copy the code

Although there are ways to skip caching, you usually don’t want to. Loading an image from the cache is much faster than the full process of pull-decode-convert to a new image.

Migrate from V3 to V4

Option (Options)

One of the bigger changes in Glide V4 is the way the Glide library handles options (centerCrop(), placeholder(), etc.). In v3, the options are handled separately by a complex set of multityped builders. In the new version, a single builder of a single type takes over a set of option objects. Glide’s Generated API makes this even easier: It merges the incoming builder’s options object with any options from the included integration libraries to produce a smooth API.

RequestBuilder

For this class of methods:

listener()
thumbnail()
load()
into()

Copy the code

In Glide V4, there is only one RequestBuilder for the type you are trying to load (Bitmap, Drawable, GifDrawable, etc.). RequestBuilder can directly access the options that affect the loading process, including the data model you want to load (URL, URI, etc.), any thumbnail requests that may exist, and any listeners. RequestBuilder is also where you start loading using into() or preload() :

RequestBuilder<Drawable> requestBuilder = Glide.with(fragment)
    .load(url);

requestBuilder
    .thumbnail(Glide.with(fragment)
        .load(thumbnailUrl))
    .listener(requestListener)
    .load(url)
    .into(imageView);
Copy the code
Request options

For this class of methods:

centerCrop()
placeholder()
error()
priority()
diskCacheStrategy()

Copy the code

Most of the options are moved into a separate object called RequestOptions,

RequestOptions options = new RequestOptions()
    .centerCrop()
    .placeholder(R.drawable.placeholder)
    .error(R.drawable.error)
    .priority(Priority.HIGH);

Copy the code

RequestOptions allows you to specify a series of options at once and then reuse them for multiple loads:

RequestOptions myOptions = new RequestOptions()
    .fitCenter()
    .override(100, 100);

Glide.with(fragment)
    .load(url)
    .apply(myOptions)
    .into(drawableView);

Glide.with(fragment)
    .asBitmap()
    .apply(myOptions)
    .load(url)
    .into(bitmapView);
Copy the code
transform

Transitions in Glide V4 now replace any Transformations you set earlier. With Glide V4, if you want to apply more than one Transformation, you need to use the Transforms () method:

Glide.with(fragment)
  .load(url)
  .apply(new RequestOptions().transforms(new CenterCrop(), new RoundedCorners(20)))
  .into(target);

Copy the code

Or use the generated API:

GlideApp.with(fragment)
  .load(url)
  .transforms(new CenterCrop(), new RoundedCorners(20))
  .into(target);

Copy the code
Decoding the format

On Glide V3, the default DecodeFormat is decodeformat.prefer_rgb_565, which will use [bitmap.config.rgb_565] unless the image contains or may contain transparent pixels. RGB_565 only uses [bitmap.config. ARGB_8888] generic memory for a given image size, but has significant quality issues for certain images, including banding and tinting. Glide now uses ARGB_8888 by default to avoid RGB_565 quality issues. As a result, picture quality is higher, but memory usage is also higher.

To change the default DecodeFormat of Glide V4 back to decodeformat. PREFER_RGB_565, apply a RequestOption in the AppGlideModule:

@GlideModule public final class YourAppGlideModule extends GlideModule { @Override public void applyOptions(Context context, GlideBuilder builder) { builder.setDefaultRequestOptions(new RequestOptions().format(DecodeFormat.PREFER_RGB_565)); }}Copy the code
Transition option

For this class of methods:

crossFade()
animate()

Copy the code

Options for controlling cross-fades and other types of transformations from placeholders to images and/or thumbnails to full images have been moved to TransitionOptions.

To apply transitions (previous animations), use one of the following options that matches the type of resource you requested:

If you want to remove the transition of any default, you can use TransitionOptions. DontTransition 17 ()].

The transition animation is applied to the request using the RequestBuilder:

Glide.with(fragment)
    .load(url)
    .transition(withCrossFade(R.anim.fade_in, 300));

Copy the code
Cross fade

Unlike Glide V3, Glide V4 will not apply cross fades or any other transition effects by default. Transitions must be applied manually on each request.

To apply a cross fade transform effect for a particular load, you can use:

import static com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions.withCrossFade;

Glide.with(fragment)
  .load(url)
  .transition(withCrossFade())
  .into(imageView);

Copy the code

Or:

Glide.with(fragment)
  .load(url)
  .transition(
      new DrawableTransitionOptions
        .crossFade())
  .into(imageView);
Copy the code
Generated API

To make it easier and easier to use Glide V4, Glide now also provides a set of apis that can be customized for applications. Applications can access the generated API by including an implementation labeled [AppGlideModule][2]. The Generated API adds a GlideApp class that provides access to the RequestBuilder and RequestOptions subclasses. Subclasses of RequestOptions contain all of the methods in RequestOptions, as well as those defined in GlideExtensions. Subclasses of RequestBuilder provide access to all methods in the generated RequestOptions without requiring you to call Apply manually.

When the Generated API is not used, the request might look like this:

Glide.with(fragment)
    .load(url)
    .apply(centerCropTransform()
        .placeholder(R.drawable.placeholder)
        .error(R.drawable.error)
        .priority(Priority.HIGH))
    .into(imageView);

Copy the code

Using the Generated API, calls to RequestOptions can be inlined:

GlideApp.with(fragment)
    .load(url)
    .centerCrop()
    .placeholder(R.drawable.placeholder)
    .error(R.drawable.error)
    .priority(Priority.HIGH)
    .into(imageView);

Copy the code

You can still use the generated RequestOptions subclass to apply the same options to multiple loads; However, the generated RequestBuilder subclass may be more convenient in most cases.

I do Android development for many years, later will be updated on android advanced UI,NDK development, performance optimization and other articles, more please pay attention to my wechat public number: thank you!


The Android thing. JPG