Search code examples
androidandroid-dialogfragment

Why DialogFragment can't be an inner class?


If I had my DialogFragment declared as an inner class I got an InstantiationException on orientation change, i.e. when instance is recreated, which says there is no public constructor, class isn't public etc. In fact everything is public, default constructor is in place. If I just move this DialogFragment to a separate file - everything goes fine. I'm not looking for a workaround, I just want to understand why this is happening.


Solution

  • This seems to be a restriction in Java based on how Fragments are created and recreated.

    It seems that all Fragments have to be reinstantiated in certain situations[1], such as orientation changes (and I would guess upon initialization, depending on how the Fragment is created). This means that it will be reinstantiated from outside your outer class. However, a non-static inner class cannot be instantiated from outside the outer class.[2] There are also other cases in which a Fragment would need to be communicated with from outside the class.[3]