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.

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...