android view ondestroy,android - Force onDestroyView on a fragment's view - Stack Overflow

在Android应用中,开发者遇到一个内存管理的问题。当用户在查看评分地点并切换到用户资料时,活动之间频繁切换,导致onSaveInstanceState经常被调用,但onDestroyView并未总是被调用,这引发内存泄漏。开发者希望通过在切换活动时强制销毁Fragment视图来解决这个问题。目前的解决方案是在切换时插入一个空Fragment来销毁视图,然后在返回时从堆栈中弹出并恢复实际的最后一个Fragment。但是,这种方法显得过于复杂。因此,开发者寻求一种更有效的方法,能够在活动停止且新活动位于其前方时,强制已停止的Fragment的视图被销毁。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I'm writing an app that loads user profiles and user's ratings for different places. The app uses fragments pervasively, and it's relatively easy to jump from a profile to a rated place.

As a user clicks a profile and gets to a rated place, they can click another profile on a rated place and go on and on.

The problem I'm having is memory related, when I'm looking at a ranked place and I click a profile, I switch from one Activity to the next. In both of these activities, after setContentView I load a fragment dynamically into layout space.

Now, as I shuttle between these activities, onSaveInstance state is almost always called, however since the Fragment displaying whatever was in the foreground before the activity switch, onDestroyView is not called.

What I would like is when onSaveInstanceState is called in these dynamic fragments, it to force onDestroyView to be called as well.

The only time onDestroyView seems to be called is when I add a Fragment to the back stack. When another activity comes to the foreground and this fragment is stopped, I'd like on DestroyView to be called as well.

The current workaround I want to implement is have an empty fragment with no view, and every time I call startActivity(Intent i), load this dummy fragment to destroy views and start the next activity. Then, when I come back, pop it off the back stack and restore the actual last fragment.

This however seems excessive. So, for a stopped fragment in a stopped activity with a new activity in front of it, how do I force it to destroy it's View?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值