Search code examples
androidanimated-gifandroid-glide

How to show random gif images with glide library?


I want to show random gif images with Glide library .

I have four gif images . Every time i want to show different gif images (out of four gif images) when app is open ?

For single gif image with glide i have used below code-

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"/>

Solution

  • You should make an array of drawables within your values directory 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>
    

    and then simply select it by doing:

    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();
    

    Also noted in this answer: how to select from resources randomly (R.drawable.xxxx)


    What this does:

    • Creates an XML array (as you know how many gifs you want)
    • Creates a TypedArray object with said array.
    • It then uses the Math class to generate a random integer based on the length of the TypedArray.
    • With that selection it then gets the resource id based on that position (in this case called choice)
    • Finally to help memory management, it then recycles the array after use.

    To expand on my comment:

    You should use the asGif() function introduced with Glide 3.0 also.