微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Android片段:真的需要空构造函数吗?

我有一个带有寻呼机和FragmentStatePagerAdapter的活动(我需要在很多页面上滑动).众所周知,这个适配器一次创建3个片段实例,一个显示,前一个和下一个.

我的活动使用只有一个构造函数的片段工作得非常好:它收到了1个参数.测试时,我开始收到臭名昭着的消息:

Unable to instantiate fragment: make sure class name exists,is public,and has an empty constructor that is public 

有趣的是,此消息仅在方向更改后才会显示,但如果方向仍然存在,应用程序才会正常工作.所以,

>当方向不变时,为什么它可以工作?
>当方向改变时,为什么会失败?
>当方向变化与刚刚创建的活动相比时,片段生命周期的活动有何不同?

非常感谢

最佳答案

is empty constructor really required?

是.

Why does it work when orientation does not change?

因为Android不会尝试重新创建您的片段.

Why does it fail when orientation is changed?

因为Android正在重新创建你的片段.

当配置发生更改(例如,方向更改)时,认情况下,Android会破坏并重新创建您的活动,并且还会破坏并重新创建该活动中的片段. “重新创建片段”部分是您需要片段上的零参数公共构造函数的原因.它也用于其他情况,例如FragmentStatePagerAdapter.

或者,引用the documentation

All subclasses of Fragment must include a public empty constructor. The framework will often re-instantiate a fragment class when needed,in particular during state restore,and needs to be able to find this constructor to instantiate it. If the empty constructor is not available,a runtime exception will occur in some cases during state restore.

原文地址:https://www.jb51.cc/android/430463.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐