简体   繁体   中英

Android create a PreferenceFragment without a PreferenceActivity

I added a side menu to my Application and I managed to change the content with fragments. Now I am trying to do the Preferences, but I don't want to use a PreferenceActivity because I want to do my application with fragments because I don't want to do the NavigationDrawer twice (For my main activity displaying the fragments and for the PreferenceActivity). I found the class PreferenceFragment but after alot of research I found out that appearantly it just is a part of the SettingsActivity and when I try to addPreferenceFromResouce in the PreferenceFragment and then launch the fragment, it crashes.

So basically I am trying to find a way to display a SettingsFragment without any extra activity just by calling fragmentManager.beginTransaction().replace(R.id.contentFrame, settingsFragment).commit() just as I do with my different fragments.

I hope I asked my question understandable (I am sorry if I didn't). Thanks for your time and your help.

I found the solution myself now. It wasn't very hard. I simply created a normal PreferenceFragment and you can use it like any other fragment without a PreferenceActivity.

public class PreferenceFragment extends android.preference.PreferenceFragment {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);
}}

I then replaced it using

getFragmentManager().beginTransaction().replace(R.id.contentFrame, preferenceFragment).commit();

as you normally would.

This worked great for me. I hope it also does for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM