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

切换明暗模式时DialogFragment安全重建及构造器异常修复咨询

问题原因

系统在配置变化(如深色/浅色模式切换)时会销毁并重建Fragment,此时系统会尝试调用Fragment的无参构造函数创建新实例。你的PictureLoaderDialogFragment只有带参数的构造函数,导致系统无法完成实例化,抛出Fragment$InstantiationException,进而引发界面全白的问题。

修复方案
  1. 给Fragment添加无参构造函数;
  2. 使用Bundle传递和保存参数,避免依赖构造函数传参(系统重建时会自动保存并恢复arguments中的数据)。
修改后的代码示例
class PictureLoaderDialogFragment : DialogFragment() {

    private var bitmapByteArray: ByteArray? = null

    companion object {
        // 定义参数key,用于Bundle中存取数据
        private const val KEY_BITMAP_BYTE_ARRAY = "bitmap_byte_array"

        @JvmStatic
        fun newInstance(bitmapByteArray: ByteArray? = null): PictureLoaderDialogFragment {
            val fragment = PictureLoaderDialogFragment()
            val args = Bundle()
            // 将字节数组存入Bundle
            bitmapByteArray?.let {
                args.putByteArray(KEY_BITMAP_BYTE_ARRAY, it)
            }
            fragment.arguments = args
            return fragment
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 从arguments中取出保存的参数
        arguments?.let {
            bitmapByteArray = it.getByteArray(KEY_BITMAP_BYTE_ARRAY)
        }
    }

    // 后续展示图片的逻辑(比如onCreateView中使用bitmapByteArray加载图片)
}
关键说明
  • 必须保留无参构造:系统重建Fragment时依赖它创建实例,即使你自己不直接调用;
  • 使用arguments传递参数:Bundle中的数据会被系统自动保存,Fragment重建后可以通过arguments恢复参数,保证数据不丢失;
  • ByteArray可以直接通过Bundle的putByteArray和getByteArray方法存取,无需额外序列化处理。

内容的提问来源于stack exchange,提问作者Mohamed Jihed Jaouadi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 13:52:15