Tablayout+viewPager2+fragment频繁切换tab导致闪退
java.lang.IllegalStateException: Fragment no longer exists for key f#0: unique id xxxxxxxx
·
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(...);
}
问题解决!记录一下
火山引擎开发者社区是火山引擎打造的AI技术生态平台,聚焦Agent与大模型开发,提供豆包系列模型(图像/视频/视觉)、智能分析与会话工具,并配套评测集、动手实验室及行业案例库。社区通过技术沙龙、挑战赛等活动促进开发者成长,新用户可领50万Tokens权益,助力构建智能应用。
更多推荐
所有评论(0)