Home > Back-end >  Gif in Fragment (AnimatedImageDrawable) Android
Gif in Fragment (AnimatedImageDrawable) Android

Time:11-04

I want to place a gif in a fragment but the gif does not show,

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    binding = DataBindingUtil.inflate(
        inflater,
        R.layout.fragment_home,
        container,
        false
    )

    val imageView: ImageView = binding.root.findViewById(R.id.imgView)

    loadGif(imageView)
    
    return inflater.inflate(R.layout.fragment_home, container, false)
}

private fun loadGif(iv: ImageView) {
    try {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            val source = ImageDecoder.createSource(resources, R.drawable.gif)
            val drawable = ImageDecoder.decodeDrawable(source)
            iv.setImageDrawable(drawable)
            if (drawable is AnimatedImageDrawable) {
                drawable.start()
            }
        }

    } catch (e: IOException) {
    }
}

Here's the catch, if I run this exact same code in an activity & call loadGif() in onCreate function it works, I tried running loadGif() in the Fragment's onCreate but it crashed because view isn't created yet.

CodePudding user response:

binding = DataBindingUtil.inflate(
    inflater,
    R.layout.fragment_home,
    container,
    false
)
val imageView: ImageView = binding.root.findViewById(R.id.imgView)
loadGif(imageView)
return inflater.inflate(R.layout.fragment_home, container, false)

You're inflating the root view, loading the gif... then ignoring all of those views and reinflating it and returning that instead. So you never loaded the gif into the correct view. You need to use either binging.inflate or inflater.inflate, not both.

  • Related