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.