java.lang.IllegalStateException: Fragment no longer exists for key f#0: unique id f34db5b2-1891-4432-94ef-62cc11200ab0

这个bug出现的原因是activity试图恢复当前fragment,但该fragment不存在导致的。网上常规办法有下边两种:

1.设置viewpager2.isSaveEnabled = false  //设置viewpager2的保存功能为禁用状态

2.重写FragmentStateAdapter中的方法:

override fun getItemId(position: Int): Long {
    return try {
        table[position].id.toLong()  // 如果 tab.id 是数字字符串,如 "1001"
    } catch (e: Exception) {
        table[position].id.hashCode().toLong()  // 否则用 hash(确保 id 唯一!)
    }
}

override fun containsItem(itemId: Long): Boolean {
    return table.any { tab ->
        try {
            tab.id.toLong() == itemId
        } catch (e: Exception) {
            tab.id.hashCode().toLong() == itemId
        }
    }
}

我遇到这个问题发生的场景是build包可以正常运行,但release包会报这个错,使用了以上两种方法都不能解决这个问题,最后推测可能跟ProGuard / R8 混淆保护规则有关,在 proguard-rules.pro中添加:

# ✅ 保护所有自定义 Fragment,防止类名、构造方法、newInstance 等被混淆
-keep public class * extends androidx.fragment.app.Fragment {
    public <init>();
    public static * newInstance(...);
}

问题解决!记录一下

Logo

中国智能体开发者社区,聚焦智能体与大模型开发,提供前沿资讯、实用工具链、开源项目及行业案例。通过技术沙龙、开发者大赛等活动,促进经验交流与协作,助力开发者快速构建创新智能应用。

更多推荐