【问题标题】:Load GIF as background in linear layout through Glide通过 Glide 在线性布局中加载 GIF 作为背景
【发布时间】:2018-11-29 14:52:10
【问题描述】:

我必须在线性布局中将 GIF 图像设置为背景。我正在使用以下代码

final LinearLayout layoutMain = (LinearLayout) findViewById(R.id.main_layout);

Glide.with(this).load(R.raw.game_screen_background)
     .into(new SimpleTarget<Drawable>() {
         @Override
         public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
             layoutMain.setBackground(resource);
         }
     });

但它没有将 GIF 设置为背景。 GIF 在 raw 文件夹中,我正在使用下面的 glide 依赖项

implementation 'com.github.bumptech.glide:glide:4.7.1'
annotationProcessor 'com.github.bumptech.glide:compiler:4.7.1'

为什么 GIF 没有加载?我错过了什么吗?

【问题讨论】:

  • 你调试过你的代码吗?也许它抛出了一些异常/错误。 ?
  • 不会进入 onResourceReady 但没有将背景设置为线性布局

标签: android gif android-glide


【解决方案1】:

我认为final 可能是导致问题的原因。您可以将其删除并尝试这样。而你就像asGif()一样失踪。 您可以像这样在 LinearLayout 中加载图像。我只是向您展示将图像设置为背景的难点。

适用于 4.X 之前的 Glide 版本

如果您提供的来源不是 Gif,可能只是普通图像,则无法注册该问题。 Glide 接受 Gif 或图像作为 load() 参数。如果你,开发者,期望 URL 是一个 Gif,而事实并非如此,Glide 不能自动检测到。因此,他们引入了一种额外的方法来强制 Glide 期待 Gif asGif(),您可以调用 asBitmap() 来保证显示为常规图像。

根据本文档https://futurestud.io/tutorials/glide-displaying-gifs-and-videos

点赞: 适用于 4.X 之前的 Glide 版本

LinearLayout layoutMain = (LinearLayout) findViewById(R.id.main_layout);


    Glide.with(this).load(R.raw.game_screen_background)
            .asGif()
            .into(new SimpleTarget<Drawable>() {
                @Override
                public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
                    layoutMain.setBackground(resource);
                }
            });

Gide v4 以后的更新:

LinearLayout layoutMain = (LinearLayout) findViewById(R.id.main_layout);
GlideApp.with(this).load(R.drawable.backgroundimage).into(new SimpleTarget<Drawable>() {
            @Override
            public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    layoutMain.setBackground(resource);
                }
            }
        });

【讨论】:

  • 嗨。我想设置 scaletype 但 centercrop 不工作,你能帮忙吗?
  • @famfamfam 你能分享一个你试过的代码吗?
猜你喜欢
  • 1970-01-01
  • 2021-03-26
  • 2021-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-22
  • 2011-11-30
  • 1970-01-01
相关资源
最近更新 更多