This will be the last article in our Glide series.

In fact, the RC version of 4.0.0 was released by Glide when the first article in this series was written. I had been working on Glide 3.7.0 at the time, and the RC version was not very stable, so the whole series was based on Glide 3.7.0.

Today, the latest version of Glide is 4.4.0, so Glide 4 is quite mature and stable. Moreover, some friends have been leaving messages asking me to talk about the use of Glide 4, because it seems that Glide 4 is a big change from Glide 3, and it is impossible to use Glide 4 after learning Glide 3.

OK, so today let’s draw a successful end to this Glide series with an article called “Let’s give you a comprehensive understanding of Glide 4”.

Glide 4 overview

As mentioned just now, some friends think that Glide 4 is very different from Glide 3, but actually it is not. The reason you get this illusion is that you move the use of Glide 3 directly to Glide 4, and the IDE gets an error, and you might think that Glide 4 has changed completely.

Actually Glide 4 is not much changed from Glide 3, you just don’t know the rules yet. Glide 4 once you understand the rules for variations to Glide 4, you will find that most of the uses of Glide 3 are generic to Glide 4.

After doing some research on Glide 4, I found that Glide 4 is not really a breakthrough upgrade, but more of a neat API optimization. Compared to the Glide 3 API, Glide 4 has been adjusted more scientifically and rationally, making legibility, writability, scalability and other aspects of a good improvement. But if you’re already familiar with Glide 3, you don’t have to switch to Glide 4, because Glide 3 does everything you can do on Glide 4, and it doesn’t offer any performance improvements.

But for those who are new to Glide, there is no need to learn Glide 3, Glide 4 is the best choice.

Now, with a basic overview of Glide 4, it’s time to start learning how to use it in the real world. As I have said, the use of Glide 4 is not much different from that of Glide 3. In the previous seven article, we have learned three basic usage of Glide, caching mechanism, the callback and monitor, image transformation, custom modules, such as usage, so today the goal of this article is very simple, is to know how to implement before on the Glide 4 studied by all functions, so let’s start now.

start

To use Glide, we first needed to introduce the library into our project. Create a new Glide4Test project and add the following dependencies to your app/build.gradle file:

Dependencies {implementation 'com. Making. Bumptech. Glide: glide: 4.4.0' annotationProcessor 'com. Making. Bumptech. Glide: the compiler: 4.4.0'}Copy the code

Note that compared to Glide 3, there is a compiler library that is used to generate the Generated API, which we will talk about later.

In addition, Glide requires web functionality, so you need to declare web permissions in androidmanifest.xml:

<uses-permission android: />
Copy the code

It’s that simple, and then we’re free to use any function that Glide has.

Loading pictures

Now let’s try using Glide to load images. For example, here is the address of a picture:

http://guolin.tech/book.png
Copy the code

Then we want to load this image in our application.

First open the layout file of your project and add a Button and an ImageView to the layout, as shown below:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Load Image"
        android:onClick="loadImage"
        />

    <ImageView
        android:id="@+id/image_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>
Copy the code

In order to display the image in the ImageView when the user clicks on the Button, we need to modify the code in the MainActivity as follows:

public class MainActivity extends AppCompatActivity { ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageView = (ImageView) findViewById(R.id.image_view); } public void loadImage(View view) { String url = "http://guolin.tech/book.png"; Glide.with(this).load(url).into(imageView); }}Copy the code

Yes, it’s that simple. Now let’s run the program, and it looks like this:

As you can see, an image from the web has been successfully downloaded and displayed in ImageView.

You’ll notice that Glide 4 is used exactly the same as Glide 3 so far, and that the core code is really just this one line:

Glide.with(this).load(url).into(imageView);
Copy the code

It’s still the traditional three steps: with(), load(), and finally into(). The interpretation of this line of code, I in the Android picture loading framework the most complete analysis (a), Glide basic usage of this article explained very clear, here is no longer repeated.

Ok, now that you have successfully started Glide 4, let’s learn more uses of Glide 4.

Placeholder figure

If you look at the effect of the web Image you just loaded, you’ll notice that after clicking the Load Image button, it takes a little while for the Image to display. This is easy to understand because downloading images from the Web takes time. Is there any way we can optimize the user experience? Sure, Glide comes with a very rich variety of API support, including the placeholder function.

As the name suggests, a placeholder is a temporary image that is displayed during image loading, and then replaced with the image to be loaded.

Glide: I have prepared a loading. JPG image to display as a placeholder map. Then modify the Glide load part of the code as follows:

RequestOptions options = new RequestOptions()
        .placeholder(R.drawable.loading);
Glide.with(this)
     .load(url)
     .apply(options)
     .into(imageView);
Copy the code

Yes, it’s that simple. Here we create a RequestOptions object, call its placeholder() method to specify the placeholder image, and pass the placeholder image resource ID into the method. Finally, add an apply() method between Glide’s three steps to apply the RequestOptions object we just created.

But if you rerun the code now and click Load Image, you probably won’t see the placeholder effect at all. Because Glide has a very powerful caching mechanism, when we just loaded the image, Glide has automatically cached it down, and the next time it is loaded, it will be directly read from the cache, and will not be downloaded from the network, so the loading speed is very fast, so the placeholder may not be able to display at all.

So we need to make a little change here to give the placeholder a chance to display, as shown below:

RequestOptions options = new RequestOptions()
        .placeholder(R.drawable.loading)
        .diskCacheStrategy(DiskCacheStrategy.NONE);
Glide.with(this)
     .load(url)
     .apply(options)
     .into(imageView);
Copy the code

As you can see, a diskCacheStrategy() method is concatenated in the RequestOptions object and the diskCacheStrategy.None parameter is passed to disable the caching function of Glide.

Glide Caching is something we’ll cover in more detail later, but this is just an extra configuration that was added to test the placeholder function, so for now you just need to know that this is the way to disable caching.

Now run the code again and it should look like this:

As you can see, when the Load Image button is clicked, a placeholder is immediately displayed and then replaced when the actual Image is loaded.

In addition to this loading placeholder, there is an exception placeholder. An abnormal placeholder is displayed if the image fails to load because of something unusual, such as a bad cell network signal.

As you can probably guess, first prepare an error. JPG image and then modify the Glide loading part of the code as shown below:

RequestOptions options = new RequestOptions()
        .placeholder(R.drawable.ic_launcher_background)
        .error(R.drawable.error)
        .diskCacheStrategy(DiskCacheStrategy.NONE);
Glide.with(this)
     .load(url)
     .apply(options)
     .into(imageView);
Copy the code

Very simply, an error() method is concatenated to specify the exception placeholder map.

In fact, if you are familiar with Glide 3, I believe you have grasped the change rule of Glide 4. In Glide 3, a series of apis like placeholder(), ERROR (), diskCacheStrategy(), and so on, are used directly in tandem with the Three-step Glide approach.

Glide 4 introduced a RequestOptions object to move the API set into RequestOptions. This has the advantage of getting rid of the long Glide load statement and also doing our own API wraparound, since RequestOptions can be passed into methods as parameters.

For example, you could write a Glide load utility class like this:

public class GlideUtil { public static void load(Context context, String url, ImageView imageView, RequestOptions options) { Glide.with(context) .load(url) .apply(options) .into(imageView); }}Copy the code

Specify image size

In fact, with Glide, you don’t need to specify the image size in most cases, because Glide will automatically size the image based on the ImageView size to ensure that the image doesn’t take up too much memory and trigger an OOM.

However, if you really need to specify a fixed size for the image, Glide still supports this feature. Modify the code for Glide loading as follows:

RequestOptions options = new RequestOptions()
        .override(200, 100);
Glide.with(this)
     .load(url)
     .apply(options)
     .into(imageView);
Copy the code

Still very simple, here we specify the size of an image using the override() method. That is, Glide will now load images in 200 by 100 pixels, regardless of the size of your ImageView.

If you want to load the original size of an image, use the target. SIZE_ORIGINAL keyword, as shown below:

RequestOptions options = new RequestOptions()
        .override(Target.SIZE_ORIGINAL);
Glide.with(this)
     .load(url)
     .apply(options)
     .into(imageView);
Copy the code

This way, Glide no longer compresses the image automatically, but loads the image to its original size. Of course, this writing method also faces higher OOM risk.

Caching mechanisms

Glide’s cache design can be said to be very advanced and well considered. For caching, Glide splits it into two modules, one memory cache and one hard disk cache.

The functions of the two cache modules are different. The main function of the memory cache is to prevent the application from repeatedly reading image data into the memory, while the main function of the disk cache is to prevent the application from repeatedly downloading and reading data from the network or other places.

It is the combination of memory cache and hard disk cache that makes Glide’s excellent picture cache effect, so next we will learn the use of these two kinds of cache respectively.

Let’s start with memory caching.

Glide, you know, automatically turns on memory caching by default. That is, when we use Glide to load an image, the image will be cached in memory, as long as it is not cleared from memory, the next time we use Glide to load the image will be read directly from memory, not from the network or hard disk again. This will undoubtedly improve the efficiency of image loading. For example, you repeatedly slide up and down in a RecyclerView, RecyclerView as long as it is Glide loaded pictures can be directly read from the memory quickly and display, thus greatly improving the user experience.

The most personal thing about Glide is that you don’t even need to write any extra code to get this convenient memory caching function automatically, because Glide already has it on by default.

So now that this feature is turned on by default, what else is there to talk about? Just one thing: If you need to disable memory caching for any particular reason, Glide provides an interface for this:

RequestOptions options = new RequestOptions()
        .skipMemoryCache(true);
Glide.with(this)
     .load(url)
     .apply(options)
     .into(imageView);
Copy the code

As you can see, Glide’s memory caching is disabled simply by calling the skipMemoryCache() method and passing true.

Let’s start with hard disk caching.

In fact, when we just learned about the placeholder function, we used the hard disk cache function. The following code was used to disable Glide’s disk caching of images:

RequestOptions options = new RequestOptions()
        .diskCacheStrategy(DiskCacheStrategy.NONE);
Glide.with(this)
     .load(url)
     .apply(options)
     .into(imageView);
Copy the code

To disable disk caching, call diskCacheStrategy() and pass diskCacheStrategy.None.

The diskCacheStrategy() method, which is basically everything about the Glide cache function, can take five arguments:

  • Diskcachestrategy. NONE: indicates that no content is cached.
  • Diskcachestrategy. DATA: indicates that only raw images are cached.
  • DiskCacheStrategy. RESOURCE: said only cache the image after the transformation.
  • Diskcachestrategy. ALL: caching both the original image and the converted image.
  • DiskCacheStrategy. AUTOMATIC: said to Glide resources according to the pictures intelligently choose to use which kind of caching strategy (the default option).

Where diskCacheStrategy. DATA corresponds to diskCacheStrategy. SOURCE in Glide 3, DiskCacheStrategy. RESOURCE corresponding to Glide 3 DiskCacheStrategy. In the RESULT. And DiskCacheStrategy. AUTOMATIC is Glide 4 additional a caching strategy, and in the case of not specified DiskCacheStrategy default is this caching strategies.

The above five parameters are not difficult to understand, but you may need to understand the concept of transformed images. It is that when we use Glide to load an image, Glide by default does not display the original image, but compresses and transforms the image (we’ll learn more about this later). In short, after a series of operations to get the picture, is called after the conversion of the picture.

Ok, so much for the Glide 4 disk cache. If you want to know more about Glide cache, you can refer to the Android picture loading framework most complete parsing (3), explore Glide cache mechanism in depth this article.

Specify load format

We all know that one of Glide’s most impressive features is the ability to load GIFs, something Picasso, which is also an excellent imageloading framework, doesn’t support.

And you don’t need to write any extra code to load GIFs with Glide; It automatically judges the image format internally. For example, we change the URL of the loading image to a GIF, as shown below:

Glide.with(this)
     .load("http://guolin.tech/test.gif")
     .into(imageView);
Copy the code

Now run the code again and it should look like this:

That is, whether we pass in a normal image or a GIF, Glide will automatically judge it and parse and display it correctly.

But what if I want to specify the loading format? For example, if I want this image to load to be a still image, I don’t need Glide to automatically determine whether it is a still image or a GIF.

It’s still very simple to do this, we just need to concatenate a new method, like this:

Glide.with(this)
     .asBitmap()
     .load("http://guolin.tech/test.gif")
     .into(imageView);
Copy the code

This method is used to load static images. Glide is not required to automatically judge the image format. If you pass in a GIF, Glide will display the first frame of the GIF, not play it.

Those of you familiar with Glide 3 will be familiar with the asBitmap() method, right? Glide 3 loads () then asBitmap(), Glide 4 loads () then asBitmap(). At first glance you might not be able to tell the difference, but you will definitely get it wrong if you write it in the wrong order.

Similarly, if we can force a static image to be loaded, we can force a dynamic image to be loaded, using asGif(). Glide 4 also adds the asFile() method and asDrawable() method, which are used to force file format loading and Drawable format loading respectively.

Callbacks and listening

Callbacks and listening are a little bit too much, so let’s break it down into four parts.

(1) into () method

We all know that Glide’s into() method can pass an ImageView. Can the into() method pass in any other arguments? Can we have Glide loaded images not be displayed in the ImageView? The answer is yes, which requires the custom Target functionality.

Glide Target: SimpleTarget: SimpleTarget: SimpleTarget: SimpleTarget: SimpleTarget: SimpleTarget: SimpleTarget

SimpleTarget<Drawable> simpleTarget = new SimpleTarget<Drawable>() { @Override public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) { imageView.setImageDrawable(resource); }}; public void loadImage(View view) { Glide.with(this) .load("http://guolin.tech/book.png") .into(simpleTarget); }Copy the code

Here we create an instance of SimpleTarget, specify that its generic type is Drawable, and override the onResourceReady() method. In the onResourceReady() method, we get the Glide loaded image object, the Drawable object passed in as the method parameter. So once you have this object you can do whatever logic you want with it, but I’m just simply displaying it in the ImageView.

The SimpleTarget implementation is created, so you just need to pass it into the into() method when the image is loaded.

Here is limited to space reasons I only demonstrated the simple use of custom Target, want to learn more relevant content can read Android picture loading framework the most complete analysis (four), play Glide callback and monitoring.

2. The preload () method

Glide load picture although very smart, it will automatically determine whether the picture has been cached, if so, directly from the cache to read, if not from the network to download. But what if I want to pre-load an image so that when I actually need to load it, I can read it directly from the cache instead of waiting for a long network load time?

Don’t worry, Glide specifically provides us with a preload interface, the preload() method, that we just need to use directly.

The preload() method has two method overloads, one with no arguments indicating the original size of the image that will be loaded, and the other with arguments specifying the width and height of the loaded image.

The preload() method is also very simple to use, simply replacing the into() method as follows:

Glide.with(this)
     .load("http://guolin.tech/book.png")
     .preload();
Copy the code

After preloading, it will be very fast to load the image again because Glide will read the image directly from the cache and display it like this:

Glide.with(this)
     .load("http://guolin.tech/book.png")
     .into(imageView);
Copy the code

3. Submit () method

Glide has always been used to bring pictures to the interface. Glide is known to cache images during loading, but where do the cache files actually exist and how do I access them directly? We don’t even know yet.

Glide designed the image loading interface to make it easier to use without having to worry too much about the underlying implementation details. But what if I want to access the image cache right now? This requires the submit() method.

The submit() method is the equivalent Glide 3 downloadOnly() method. Similar to the Preload () method, the submit() method can also replace into(). However, the use of the submit() method is significantly more complicated than that of the preload() method. This method only downloads images, not loads them. When the image is downloaded, we can get the image storage path for subsequent operations.

So first let’s look at the basic usage. The submit() method has two method overloads:

  • submit()
  • submit(int width, int height)

The submit() method is used to download the original size of the image, and submit(int width, int height) can specify the size of the image to download.

Take the submit() method as an example. When the Submit () method is called, a FutureTarget object is immediately returned, and Glide begins downloading the image file in the background. We then call FutureTarget’s get() method to retrieve the downloaded image file. If the image has not been downloaded, the get() method will block and return a value until the image has been downloaded.

Let’s use an example to demonstrate this. The code looks like this:

public void downloadImage() { new Thread(new Runnable() { @Override public void run() { try { String url = "http://www.guolin.tech/book.png"; final Context context = getApplicationContext(); FutureTarget<File> target = Glide.with(context) .asFile() .load(url) .submit(); final File imageFile = target.get(); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(context, imageFile.getPath(), Toast.LENGTH_LONG).show(); }}); } catch (Exception e) { e.printStackTrace(); } } }).start(); }Copy the code

This code is a little bit longer, so LET me walk you through it. First, the submit() method must be used in the child Thread, since FutureTarget’s get() method blocks the Thread, so the first step is to create a new Thread. In the child thread, we get an Application Context first, and we can’t use the Activity as the Context anymore, because there’s a chance that the Activity has been destroyed before the child thread has finished executing.

Next comes the basic use of Glide, which replaces the into() method with the submit() method and uses an asFile() method to specify the load format. The Submit () method returns a FutureTarget object, by which time Glide has already downloaded the image in the background. We can call FutureTarget’s Get () method at any time to retrieve the downloaded image file. However, if the image has not been downloaded, the thread will temporarily block and return the image’s File object when the download is complete.

Finally, we use runOnUiThread() to cut back to the main thread, and then use Toast to display the downloaded image file path.

Now run the code again to see what it looks like below.

So we can clearly see what the full cache path of the image is.

4. The listener () method

In fact, the listener() method is very common. It can be used to listen for the state of Glide loading images. For example, let’s say we just used the preload() method to preload images, but how do I know if the preload is complete? And if Glide load picture fails, how do I debug the cause of the error? The answers are in the listener() method.

Instead of replacing into(), the listener() method is used in conjunction with the into() method, or with the preload() method. The most basic usage is as follows:

Glide.with(this)
     .load("http://www.guolin.tech/book.png")
     .listener(new RequestListener<Drawable>() {
         @Override
         public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
             return false;
         }

         @Override
         public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
             return false;
         }
     })
     .into(imageView);
Copy the code

Here we concatenate a listener() method before the into() method, and then implement an instance of RequestListener. RequestListener implements two methods, onResourceReady() and onLoadFailed(). As you can see from the name of the method, onResourceReady() is called when the image load is complete and onLoadFailed() is called when the image load fails. The onLoadFailed() method passes in the failed GlideException parameter so that we can locate the specific cause of the failure.

Yes, the listener() method is that simple. The onResourceReady() and onLoadFailed() methods both return a Boolean value, false to indicate that the event was not handled, which is passed down, and true to indicate that the event was handled. So it doesn’t pass any further down. For a simpler example, if we return true in the onResourceReady() method of the RequestListener, then the onResourceReady() method of Target will not be called again.

About callback and monitor content so much, if you want to learn more in-depth content and source code analysis, or please refer to this article Android picture loading framework most complete analysis (four), play Glide callback and monitor.

Image transform

Picture transformation means that Glide from loading the original picture to the final display to the user before, and some transformation processing, so as to achieve some more rich picture effects, such as picture rounded, rounded, blurred and so on.

Adding the transforms is very simple. We simply concatenate the transforms() method in RequestOptions and pass the requested transforms as a parameter to it, as shown below:

RequestOptions options = new RequestOptions() .transforms(...) ; Glide.with(this) .load(url) .apply(options) .into(imageView);Copy the code

As for the specific picture transformation operation, this is usually needed to write our own. But Glide already has several image transformations built into it that we can use directly, such as CenterCrop, FitCenter, CircleCrop, and so on.

Transform () is not required for any of the built-in image transformation operations. Glide provides a ready-made API for us to use:

RequestOptions options = new RequestOptions()
        .centerCrop();

RequestOptions options = new RequestOptions()
        .fitCenter();

RequestOptions options = new RequestOptions()
        .circleCrop();
Copy the code

Of course, these built-in image transform apis are really just a wrapper around the transform() method, and the source code behind them is still implemented using the transform() method.

CircleCrop () is a circleCrop() method used to crop a circular image. Let’s try it out, as shown below:

String url = "http://guolin.tech/book.png";
RequestOptions options = new RequestOptions()
        .circleCrop();
Glide.with(this)
     .load(url)
     .apply(options)
     .into(imageView);
Copy the code

Run the program again and click the load image button. The result is as shown below.

As you can see, the image shown here is a circular clipping of the original image.

Of course, in addition to using the built-in image transform operation, we can completely customize our own image transform operation. In theory, you can do anything you want with the image transformation step. This can include rounded corners, circles, black and white, blurs, and even completely replacing the original image with another one.

But since this is not a change from Glide 3, we won’t repeat it. Want to learn custom picture conversion operation friends can refer to this article Android picture loading framework most complete analysis (five), Glide powerful picture conversion function.

Glide – doubling is a quick and easy way to make transformations. It has realized a lot of general image transformation effects, such as cropping transformation, color transformation, fuzzy transformation and so on, so that we can be very easy to carry out a variety of image transformation.

Glide – Doubling projects homepage is github.com/wasabeef/gl… .

Let’s take a look at the power of this library. First we need to introduce this library into our project by adding the following dependencies to our app/build.gradle file:

Double double = double double = double double = double doubleCopy the code

We can do a single image transformation process, or we can use multiple image transformation together. For example, if I want to blur and black and white an image at the same time, I can say:

String url = "http://guolin.tech/book.png";
RequestOptions options = new RequestOptions()
        .transforms(new BlurTransformation(), new GrayscaleTransformation());
Glide.with(this)
     .load(url)
     .apply(options)
     .into(imageView);
Copy the code

As you can see, when multiple image transformations are performed simultaneously, you simply pass them all into the Transforms () method. Now run the program again. The result should look like the following image.

This is just a small part of glide- Transformations, you can learn more about them on the GitHub website.

Custom modules

The custom module belongs to the advanced function of Glide, and it is also a part of the higher difficulty.

It is impossible for me to cover all the contents of the custom module in this article. Due to the limited space, I can only talk about this part of the changes in Glide 4. About the whole content of Glide custom module, please refer to the Android picture loading framework most complete analysis (six), explore the function of Glide custom module this article.

The custom module function can change The Glide configuration, replace the Glide components and other operations independently, so that we can easily customize the various configurations of Glide, and Glide picture loading logic without any intersection, which is also a low coupling programming way. Let’s take a look at how custom modules are implemented.

Start by defining a module class of our own and having it inherit from AppGlideModule, as follows:

@GlideModule
public class MyAppGlideModule extends AppGlideModule {

    @Override
    public void applyOptions(Context context, GlideBuilder builder) {

    }

    @Override
    public void registerComponents(Context context, Glide glide, Registry registry) {

    }

}
Copy the code

As you can see, in the MyAppGlideModule class, we overwrote the applyOptions() and registerComponents() methods, which are used to change Glide configuration and replace Glide components, respectively.

Note that on the MyAppGlideModule class, we added a @glidemodule annotation. This is one of the biggest differences between Gilde 4 and Glide 3. In Glide 3, after we defined a custom module, we had to register it in the Androidmanifest.xml file to take effect, which is not required in Glide 4. The @glidemodule annotation already allows Glide to recognize this custom module.

In this way, we have finished the function of Glide custom module. You can then change the Glide configuration or replace the Glide components by adding specific logic to the applyOptions() and registerComponents() methods. For details, please refer to the Android picture loading framework most complete analysis (six), explore Glide’s custom module function of this article, here will not be discussed.

Using the Generated API

The Generated API is a new feature introduced in Glide 4. It works by using the Annotation Processor to generate an API, The streaming API can be used in the Application module to call all the options in the RequestBuilder, RequestOptions, and integration library at once.

It’s a bit of a mouthful, but the bottom line is that Glide 4 still gives us the same set of streaming apis as Glide 3. After all, some people, like me, find Glide 3’s API better to use.

The Generated API is the same as GlideApp, and the Generated API is the same as GlideApp, and the Generated API is the same as GlideApp.

GlideApp.with(this)
        .load(url)
        .placeholder(R.drawable.loading)
        .error(R.drawable.error)
        .skipMemoryCache(true)
        .diskCacheStrategy(DiskCacheStrategy.NONE)
        .override(Target.SIZE_ORIGINAL)
        .circleCrop()
        .into(imageView);
Copy the code

However, it is possible that your IDE will tell you that the GlideApp class cannot be found. This class is automatically generated by compile-time annotations. First, make sure you have a custom module in your code and add the @glidemodule annotation to it, which we discussed in the previous section. Then click on the Build -> Rebuild Project menu bar in Android Studio and the GlideApp class will be automatically generated.

Of course, the Generated API does more than that. It also extends existing apis to create any of your own.

DiskCacheStrategy (diskCacheStrategy.data) : CacheStrategy.data: cacheStrategy.data: cacheStrategy.data: cacheStrategy.data: cacheStrategy.data: cacheStrategy.data It was a little upsetting. In this case, we can customize our own API.

Customizing your API requires the annotation @glideExtension and @glideOption. Create a custom extension class as follows:

@GlideExtension public class MyGlideExtension { private MyGlideExtension() { } @GlideOption public static void cacheSource(RequestOptions options) { options.diskCacheStrategy(DiskCacheStrategy.DATA); }}Copy the code

Here we define a MyGlideExtension class, add an @glideExtension annotation, and declare the constructor of the class private, which is required.

We’re ready to customize the API. Here we define a cacheSource() method to cache only raw images and annotate it with @glideOption. Note that all custom API methods must be static, and the first argument must be RequestOptions, after which you can add as many custom parameters as you want.

In the cacheSource() method, we are still calling the diskCacheStrategy(DiskCacheStrategy.data) method, so cacheSource() is simply a wrapper around a simplified API.

Then click on the Build -> Rebuild Project menu bar in Android Studio and the magic will happen. You will find that you can already load images with statements like:

GlideApp.with(this)
        .load(url)
        .cacheSource()
        .into(imageView);
Copy the code

With this powerful function, we can be more flexible with Glide.

conclusion

This has almost covered all the important elements of Glide 4, and if you are familiar with Glide 3 before, you will be able to use it proficiently by the end of this article. And if you have not touched Glide before, just look at this article may not understand enough, it is best to read the first seven articles also go through, so that you can become a Glide hand.

I checked the historical records and posted the first article in this series on March 21 this year. It took me 10 months to complete the series. At that time, I promised to write eight articles, and now I have fulfilled my promise. I hope to continue to bring you better technical articles in the future, but that’s the end of this series. And thank you to the patient friends who could see it to the end, those of you who could stick it out, you’re all as good as ME.

Pay attention to my technical public account “Guo Lin”, there are high-quality technical articles pushed every day. Pay attention to my entertainment public number, work, study tired when relax yourself.