如何使用 glide 库显示随机 gif 图像?

How to show random gif images with glide library?

我想用 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"/>

创建可绘制对象数组:

 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 class 的 nextInt 方法生成一个介于 0(含)和给定参数(不含)之间的数字。

在 glide 库中使用:

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

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

您应该在您的值目录中创建一个可绘制对象数组 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>

然后简单地 select 这样做:

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 class根据TypedArray的长度生成一个随机整数。
  • 有了那个 selection,然后它根据那个位置获取资源 ID(在本例中称为 choice
  • 最后为了帮助内存管理,它会在使用后回收数组。

扩展我的评论:

您还应该使用 Glide 3.0 引入的 asGif() 函数。