1

I have a Fragment that overrides the public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) method without a call to super like this:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.my_id, container, false);
        return view;
    }

This fragment is used both in activities and in a custom DialogPreference implementation. The fragment is included in the layout files for the activities and the preference with the <fragment> tag and has an android:id attribute in both (though the id is different for the activity- and preference-layout).

The custom DialogPreference is used within a PreferenceFragment and everything works as intended. When I click on the custom Preference in the PreferenceScreen, the onCreateView method is called and the DialogFragment with my Fragment inside is displayed correctly. When I press back, the Dialog closes and the PreferenceScreen is shown again. On the next click, onCreateView is called again and everything displays fine.

Now I am trying to add a "RetainedFragment" to this Fragment to store some state as explained here. To achive this, I have overwritten onCreate in my fragment like this:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FragmentManager fm = getFragmentManager();
    retainedFragment = (RetainedFragment) fm.findFragmentByTag("retained");
    if(retainedFragment == null) {
        retainedFragment = new RetainedFragment();
        fm.beginTransaction().add(retainedFragment, "retained").commit();
    }
}

This works perfectly for the Activity case, but now, when I try to open the DialogPreference two times in a row, the app crashes with

java.lang.IllegalStateException: 
Fragment com.myapp.MyFragment did not create a view

I set some breakpoints, and the problem seems to be that the onCreateView method of my fragment is only called the first time I click on my DialogPreference after the PreferenceScreen is opened. When I close the PreferenceScreen in between, it also works ok.

It is noteworthy that the Exception occurs for the initial Fragment, not the new "RetainedFragment".

feob
  • 1,930
  • 5
  • 19
  • 31

0 Answers0