Xiaosheng Wilson Wu Xiaosheng Wilson Wu - 6 months ago 19
Android Question

creating a fragment from a fragment without using fragment manager

I am trying to call a fragment with code like this

SettingsFragment fragment = new SettingsFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
.replace(R.id.fragment_container, fragment, SETTINGS_FRAGMENT_TAG)

However, since I changed "extends Fragment" to "PreferenceFragment" in my SettingFragment I use

public class SettingsFragment extends PreferenceFragment {}

this line is giving me the error that my second argument "fragment" requires "android.support.v4.app.Fragment" After adding this lib it's still not working

.replace(R.id.fragment_container, fragment, SETTINGS_FRAGMENT_TAG)

It looks like my fragmentManager is confusing about my fragment... Is there a way to solve this problem or even not using the fragmentManager? Thanks


The PreferenceFragment extends android.app.Fragment. In order to use the support FragmentManager, you must use a class that extends the android.support.v4.app.Fragment, as @NoChinDeluxe suggested.

I suggest using the v7 Preference Support Libarary:

compile 'com.android.support:preference-v7:24.0.0'

This library includes the PreferenceFragmentCompat class, which extends android.support.v4.app.Fragment. Therefore you can extend this class, instead of PreferenceFragment to use your SettingsFragment with the support FragmentManager.