简体   繁体   English

什么时候不能使用onRetainNonConfigurationInstance()

[英]When is it NOT okay to use onRetainNonConfigurationInstance()

Documentation of onRetainNonConfigurationInstance() says "This function is called purely as an optimization, and you must not rely on it being called." onRetainNonConfigurationInstance()文档说“这个函数纯粹被称为优化,你不能依赖它被调用。”

Under what circumstances will onRetainNonConfigurationInstance() not be called? 什么情况下onRetainNonConfigurationInstance()不会被调用?

Some background on what I am trying to achieve: I want to my activity to be notified of orientation change reliably (but also want activity to be killed & restarted as usual) . 关于我想要实现的目标的一些背景:我希望我的activity可靠地通知orientation变化(但也希望活动像往常一样被杀死和重新启动)

if you want the activity to restart (calling onCreate->onResume) again on orientation change you don't place configChanges="orientation" in the manifest. 如果您希望在方向更改时重新启动活动(再次调用onCreate-> onResume),则不要在清单中放置configChanges =“orientation”。 you can check the orientation of the screen in the onCreate method of your activity which is probably what you need. 您可以在活动的onCreate方法中检查屏幕的方向,这可能就是您所需要的。 if you dont want the activity to restart itself but rather just switch orientation then you add the configChanges flag in the manifest for the activity and then only onConfigurationChanged() will be called where you also can get the screen orientation. 如果您不希望活动重新启动,而只是切换方向,那么您在活动清单中添加configChanges标志,然后只调用onConfigurationChanged(),您也可以获得屏幕方向。 the second way is good when you have expensive operations running in the onCreate methods (starting threads quering databases etc) and you want to reuse that info/data for portrait and for landscape. 当您在onCreate方法中运行昂贵的操作(启动线程查询数据库等)并且您希望将该信息/数据重用于纵向和横向时,第二种方法是好的。 even if you want you can change the layout in onConfigurationChanged() the same way its done in on create but you again need to find the references to all the views because their ids are not the same in that case. 即使你想要你可以改变onConfigurationChanged()中的布局,就像它在创建时所做的那样,但是你再次需要找到对所有视图的引用,因为它们的id在这种情况下是不一样的。

In any case if you want to have a reference to something that existed before the orentation change the configChanges way is better for handling the changes but it requires a bit more work if you are changing layouts or something. 在任何情况下,如果您想要在更改之前存在对某些内容的引用,那么configChanges方式更适合处理更改,但如果您要更改布局或其他内容,则需要更多工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM