【问题标题】:How to show random gif images with glide library?如何使用 glide 库显示随机 gif 图像?
【发布时间】:2017-04-12 09:23:07
【问题描述】:

我想用 Glide 库显示随机 gif 图像。

我有四个 gif 图片。每次我想在应用打开时显示不同的 gif 图像(四张 gif 图像)?

对于带有滑动的单个 gif 图像,我使用了下面的代码-

protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ImageView imageView = (ImageView) findViewById(R.id.my_image_view);
    GlideDrawableImageViewTarget imageViewTarget = new GlideDrawableImageViewTarget(imageView);
    Glide.with(this).load(R.drawable.dancingbanana).into(imageViewTarget);
}

activiy_main

<ImageView
android:id="@+id/my_image_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

【问题讨论】:

  • 使用 load(...).asGif().into(imageViewTarget);
  • 制作一个R.drawables数组,然后打乱它们,然后访问第一个
  • 这样我只能给出一张图片但是我想给出四种不同类型的gif图片
  • gif 图像的类型?
  • 我希望 gif 图像是随机的

标签: android animated-gif android-glide


【解决方案1】:

你应该在你的值目录res/values/arrays.xml中创建一个可绘制数组

<array name="gif_drawables">
    <item>@drawable/gif_1</item>
    <item>@drawable/gif_2</item>
    <item>@drawable/gif_3</item>
    <item>@drawable/gif_4</item>
</array>

然后简单地选择它:

TypedArray images = getResources().obtainTypedArray(R.array.gif_drawables);
int choice = (int) (Math.random() * images.length());
ImageView imageView = (ImageView) findViewById(R.id.my_image_view);
GlideDrawableImageViewTarget imageViewTarget = new GlideDrawableImageViewTarget(imageView);
Glide.with(this).load(images.getResourceId(choice, R.drawable.gif_1)).asGif().into(imageViewTarget);
images.recycle();

在这个答案中也提到:how to select from resources randomly (R.drawable.xxxx)


这是做什么的:

  • 创建一个 XML 数组(你知道你想要多少个 gif)
  • 使用所述数组创建TypedArray 对象。
  • 然后它使用Math 类根据TypedArray 的长度生成一个随机整数。
  • 通过该选择,它会根据该位置获取资源 ID(在本例中称为 choice
  • 最后帮助内存管理,然后在使用后回收阵列。

扩展我的评论:

你也应该使用Glide 3.0引入的asGif()函数。

【讨论】:

    【解决方案2】:

    制作一个可绘制数组:

     private Integer[] mThumbIds = {
                R.drawable.sample_2, R.drawable.sample_3,
                R.drawable.sample_4, R.drawable.sample_5,
                R.drawable.sample_6, R.drawable.sample_7,
                R.drawable.sample_0, R.drawable.sample_1,
                R.drawable.sample_2, R.drawable.sample_3,
    
        };
    

    然后随机选择图像:

    Random random = new Random();
    int indexToGetImageFrom = random.nextInt(sizeOfYourArray);
    

    上面的代码会为你生成一个随机数。 Random 类的 nextInt 方法生成一个介于 0(包括)和给定参数(不包括)之间的数字。

    在滑翔库中使用:

    Glide.with(this).load(mThumbIds[ i ]).into(imageViewTarget);其中 i 是 indexToGetImageFrom

    每次都会生成一个新数字并显示一个新的图像视图。

    【讨论】:

    • 我正在使用 gif 图像进行随机化,因此我使用了 Glide 库
    • Glide.with(this).load(mThumbIds[ i ]).into(imageViewTarget);其中 i 是 indexToGetImageFrom 。
    猜你喜欢
    • 2015-09-13
    • 2017-08-01
    • 1970-01-01
    • 2019-04-30
    • 1970-01-01
    • 2018-03-04
    • 1970-01-01
    • 2020-12-18
    • 2020-04-25
    相关资源
    最近更新 更多