片段中的 Gif (AnimatedImageDrawable) Android

Gif in Fragment (AnimatedImageDrawable) Android

我想在片段中放置一个 gif,但是 gif 没有显示,

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) {
    }
}

关键在于,如果我 运行 在 activity 中使用完全相同的代码并在 onCreate 函数中调用 loadGif() ,我尝试了 运行ning loadGif() Fragment 的 onCreate 但由于尚未创建视图而崩溃。

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)

您正在膨胀根视图,加载 gif...然后忽略所有这些视图并重新膨胀它并返回它。所以你从来没有将 gif 加载到正确的视图中。您需要使用 binging.inflate 或 inflater.inflate,不能同时使用。