Search code examples
androidandroid-view

Most efficient way to show a loading spinner - Android


I am building an app that contains a lot of views that need to be loaded from a remote server. Therefore, a loading spinner like this one will be used as a placeholder for it until it's fully loaded. This is how I am doing it :

1- First, I use a spinner.gif file which I placed in the res/raw folder. I am really not restricted to only this file. I want any spinner view/animation that shows there is something that is being loaded.

2- Then, I literally added Glide as a dependency just to show these GIFs. The library itself takes up a considerable space of my app size. This is the code I use:

val gif = findViewById<ImageView>(rr.id.gif)
=Glide.with(context)
            .asGif()
            .load(rr.raw.spinner)
            .apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.NONE))
            .listener(object : RequestListener<GifDrawable?> {
                override fun onLoadFailed(
                    e: GlideException?,
                    model: Any?,
                    target: Target<GifDrawable?>?,
                    isFirstResource: Boolean
                ): Boolean {
                    return false
                }

                override fun onResourceReady(
                    resource: GifDrawable?,
                    model: Any?,
                    target: Target<GifDrawable?>?,
                    dataSource: DataSource?,
                    isFirstResource: Boolean
                ): Boolean {
                    resource?.setLoopCount(999999999)
                    return false
                }
            })
            .into(gif)

I believe this is overkill just to load a spinner GIF. Is there a more efficient way to show a spinner animation (of any kind) that saves me in terms of performance and app size? I have tried using ProgressBar but it's just a horizontal bar that loads according to the values passed to it.


Solution

  • By default a ProgressBar is a circular, indeterminate one (i.e. it doesn't show an amount of progress, it just spins to show activity). Just stick one in your layout with a width and height and that's all you need! You can see some options for customising it (including with your own drawable) on the docs page.

    If you like, the Material Components library has its own progress spinners - for those you do need to set indeterminate to true, they're determinate by default.