Android 11设备中Fragment通过Adapter显示Toast崩溃求助
解决方案
1. 绑定协程到Fragment生命周期
你当前使用的CoroutineScope(Dispatchers.Main).launch未关联Fragment生命周期,可能导致Fragment状态异常时执行Toast引发问题。改用viewLifecycleOwner.lifecycleScope,确保协程仅在Fragment活跃时运行,同时增加Fragment状态校验:
private val adapterActions = object : TestimonialAdapterActions{ override fun onTestimonialPosted(content: String) { postTestimonial.expertId = userId postTestimonial.userId = userModel?.id ?: 0 postTestimonial.content = content viewLifecycleOwner.lifecycleScope.launch { val resp = apiManager.postTestimonial(postTestimonial, userId, requireContext()) if(resp.getInt("status") != 0){ if(isAdded){ Toast.makeText(requireContext(), "Success", Toast.LENGTH_SHORT).show() } testimonialsAdapter.refresh() } else{ if(isAdded){ Toast.makeText(requireContext(), "Something went wrong!", Toast.LENGTH_SHORT).show() } } } } }
2. 替换Toast为Snackbar(推荐)
Toast在Android 11的跨用户场景下易触发权限异常,而Snackbar依赖Activity视图,无此类权限问题:
// 成功提示 if(isAdded){ Snackbar.make(requireView(), "Success", Snackbar.LENGTH_SHORT).show() } // 失败提示 if(isAdded){ Snackbar.make(requireView(), "Something went wrong!", Snackbar.LENGTH_SHORT).show() }
3. 严格校验Context有效性
显示Toast前,确保Fragment已绑定Activity且Context未销毁:
if(isAdded && !requireContext().isFinishing && !requireContext().isDestroyed){ Toast.makeText(requireContext(), "提示内容", Toast.LENGTH_SHORT).show() }
注意:权限不可申请
错误日志中提到的INTERACT_ACROSS_USERS或INTERACT_ACROSS_USERS_FULL为系统级权限,普通应用无法通过清单文件申请,此路径无法解决问题。
内容的提问来源于stack exchange,提问作者Sajal Jain
相关产品推荐
相关产品推荐

