Skip to content Skip to sidebar Skip to footer

Dialogfragment Behaving Unexpectedly

Hi I have used this DialogFragment to display date picker in my app public class DateDialogFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener{

Solution 1:

The reason you are seeing this is because Android sometimes needs to instantiate that Fragment on its own. This applies to anyFragment.

When you create a static inner class, that means it is not tied to any specific instance of the outer class. So let's say you have:

publicclassA {
  publicstaticclassB {
    // ...
  }
  publicclassC {
    // ...
  }
}

In this case, you cannot do new C() from outside A because all instances of C belong to an A object. You can, however, do new B() or new A.B().

The same applies to the fragment; Android cannot do new DateDialogFragment() if the class is not static. The reason you are not getting an error (though Lint should be telling you) is because you are instantiating the DateDialogFragment yourself.

However, if you trigger something like an orientation change and don't recreate the Fragment manually, Android will do it for you. Being unable to do so, it will crash.

If the class is static, however, Android can create an instance of it. Therefore, a nested Fragment class should always be static.

Post a Comment for "Dialogfragment Behaving Unexpectedly"