Search code examples
androidandroid-fragmentsandroid-fragmentactivityandroid-preferences

How to make a PreferenceFragment work with the MainActivity


In my MainActivity onCreate method, I have

getFragmentManager()
    .beginTransaction()
    .add(android.R.id.content, new MyPreferenceFragment())
    .commit();

What this does is adding the PreferenceFragment to my app's content ViewGroup but it makes also the MainActivity's content inaccessible (the buttons can no longer be clicked).

My question is: is there a way to make a PreferenceFragment work with the MainActivity so that both Activity and Fragment are accessible?

Thanks Jon


Solution

  • You can inflate your Fragment into a container view.

    To do this, add a ViewGroup to your Activitie's layout file, for example:

    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    

    And use this in your Activity:

    getFragmentManager()
          .beginTransaction()
          .add(R.id.container, new MyPreferenceFragment())
          .commit();
    

    Now you can just show the Fragment in the given container without overwriting the layout of the MainActivity.