You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android中Fragment使用AnimatedImageDrawable加载GIF不显示如何解决?

问题原因
  • 核心错误是onCreateView方法中存在两次布局加载逻辑:你首次通过DataBindingUtil.inflate加载了布局实例,在该实例的ImageView上完成了GIF加载配置,但最终返回给Fragment渲染的是第二次调用inflater.inflate生成的全新布局实例,这个新实例的ImageView没有做任何GIF加载处理,因此无法显示GIF。
  • Activity中代码可正常运行是因为Activity的onCreate仅加载一次布局,所有视图操作都作用在最终显示的布局实例上,不存在重复加载覆盖操作的问题。
  • 你在onCreate中调用loadGif崩溃是因为Fragment的onCreate生命周期早于视图创建阶段,此时无法获取到布局中的ImageView控件,会触发空指针异常。
解决方法

修正后的代码如下:

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    binding = DataBindingUtil.inflate(
        inflater,
        R.layout.fragment_home,
        container,
        false
    )
    // 直接返回绑定后的根视图,不要重新inflate
    return binding.root
}

// 推荐将视图操作放在onViewCreated中,逻辑更清晰,避免视图未初始化问题
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    // 可以直接通过binding获取控件,不需要额外findViewById
    loadGif(binding.imgView)
}

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) {
        e.printStackTrace()
    }
}

额外优化说明:

  • 如果你需要兼容Android 9(API 28)以下的系统版本,可以使用通用图片加载库加载GIF,无需做系统版本判断。
  • 空的catch块会屏蔽异常信息,不利于后续问题排查,建议添加异常日志打印逻辑。

内容的提问来源于stack exchange,提问作者Edvin Keskin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 20:36:04