Android使用glide加载gif动画设置播放次数

连接:https://www.jb51.net/article/98570.htm

 

在使用glide加载gif动画,有时需要设置播放的次数,然后播放玩一次或者几次之后,需要在播放完做一些其他的操作,直接看代码:

Glide.with(this)

        .load(R.drawable.xiaoguo)

        .diskCacheStrategy(DiskCacheStrategy.SOURCE)

        .listener(new RequestListener() {

 

          @Override

          public boolean onException(Exception arg0, Integer arg1,

              Target arg2, boolean arg3) {

            return false;

          }

 

          @Override

          public boolean onResourceReady(GlideDrawable resource,

              Integer model, Target target,

              boolean isFromMemoryCache, boolean isFirstResource) {

            // 计算动画时长

            GifDrawable drawable = (GifDrawable) resource;

            GifDecoder decoder = drawable.getDecoder();

            for (int i = 0; i < drawable.getFrameCount(); i++) {

              duration += decoder.getDelay(i);

            }

            //发送延时消息,通知动画结束

            handler.sendEmptyMessageDelayed(MESSAGE_SUCCESS,

                duration);

            return false;

          }

        }) //仅仅加载一次gif动画

        .into(new GlideDrawableImageViewTarget(imageview, 1));

解决加载gif文件非常慢的情况: 

为其添加缓存策略

 

复制代码代码如下:

Glide.with(MainActivity.this).load(url).asGif().diskCacheStrategy(DiskCacheStrategy.SOURCE).into(imageView); 

 

其中缓存策略可以为:Source及None,None及为不缓存,Source缓存原型.如果为ALL和Result就不行 
DiskCacheStrategy.NONE 什么都不缓存 
DiskCacheStrategy.SOURCE 仅仅只缓存原来的全分辨率的图像。 
DiskCacheStrategy.RESULT 仅仅缓存最终的图像,即,降低分辨率后的(或者是转换后的) 
DiskCacheStrategy.ALL 缓存所有版本的图像(默认行为)

设置gif播放次数: 

这样写会报错的:

Glide.with(MainActivity.this).load(url).asGif().into(new GlideDrawableImageViewTarget(imageview, 1));

设置播放次数和播放监听的时候,不应加上.asGif()

Glide.with(MainActivity.this).load(url).into(new GlideDrawableImageViewTarget(imageview, 1));

new GlideDrawableImageViewTarget(imageview, 1),imageview是控件,1是播放次数

设置播放监听: 

添加listener()

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

listener(new RequestListener() {

 

          @Override//加载出错

          public boolean onException(Exception arg0, Integer arg1,

              Target arg2, boolean arg3) {

            return false;

          }

 

          @Override//加载完成

          public boolean onResourceReady(GlideDrawable resource,

              Integer model, Target target,

              boolean isFromMemoryCache, boolean isFirstResource) {

            // 计算动画时长

            GifDrawable drawable = (GifDrawable) resource;

            GifDecoder decoder = drawable.getDecoder();

            for (int i = 0; i < drawable.getFrameCount(); i++) {

              duration += decoder.getDelay(i);

            }

            //发送延时消息,通知动画结束

            handler.sendEmptyMessageDelayed(MESSAGE_SUCCESS,

                duration);

            return false;

          }

        })

你可能感兴趣的:(移动,Android)