Luca Vinciguerra
Luca Vinciguerra

Reputation: 37

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.

Upvotes: 1

Views: 1058

Answers (1)

Luca Vinciguerra
Luca Vinciguerra

Reputation: 37

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.

Upvotes: 1

Related Questions