Android片段:真的需要空构造函数吗? [英] Android fragments: is empty constructor really required?

查看:57
本文介绍了Android片段:真的需要空构造函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an activity with a pager and a FragmentStatePagerAdapter inside (I need to swipe across many pages). As we all know, this adapter creates 3 fragment instances at a time, the one to be displayed, the previous and next ones.

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

My activity was working really nice using a fragment with only one constructor: it received 1 parameter. When testing, I started to get the infamous message:

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

有趣的是,此消息仅在方向更改后立即显示,但该应用程序仅在方向保持不变时才起作用.因此,

The funny part is that this message only shows up right after orientation change, but the app just works if orientation remains still. So,

  1. 当方向不变时,为什么它起作用?
  2. 为什么更改方向后会失败?
  3. 方向改变与刚创建的活动相比,片段生命周期的活动有何不同?

非常感谢

推荐答案

真的需要空的构造函数吗?

is empty constructor really required?

是的

当方向不变时,为什么它起作用?

Why does it work when orientation does not change?

因为Android并未尝试重新创建片段.

Because Android is not trying to recreate your fragments.

为什么更改方向后会失败?

Why does it fail when orientation is changed?

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

Because Android is recreating your fragments.

发生配置更改(例如方向更改)时,默认情况下,Android会销毁并重新创建您的活动,并销毁并重新创建该活动中的片段.重新创建片段"部分是为什么在片段上需要零参数的公共构造函数的原因.在其他情况下也可以使用它,例如 FragmentStatePagerAdapter .

When a configuration change occurs (e.g., orientation change), by default Android destroys and recreates your activity, and also destroys and recreates the fragments in that activity. The "recreates the fragments" part is why you need the zero-argument public constructor on your fragments. It is also used in other cases, such as with a FragmentStatePagerAdapter.

或者引用文档:

Fragment的所有子类都必须包含一个公共的空构造函数.框架通常会在需要时重新实例化片段类,尤其是在状态还原期间,并且需要能够找到此构造函数以实例化它.如果空的构造函数不可用,则在状态还原期间某些情况下会发生运行时异常.

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片段:真的需要空构造函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆