Android fragments: is empty constructor really required?

前端 未结 1 1860
终归单人心
终归单人心 2021-02-10 01:33

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,

1条回答
  •  深忆病人
    2021-02-10 02:07

    is empty constructor really required?

    Yes.

    Why does it work when orientation does not change?

    Because Android is not trying to recreate your fragments.

    Why does it fail when orientation is changed?

    Because Android is recreating your fragments.

    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.

    Or, to quote 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.

    0 讨论(0)
提交回复
热议问题