John Smith
John Smith

Reputation: 874

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

Upvotes: 2

Views: 820

Answers (2)

Kumar Shashwat
Kumar Shashwat

Reputation: 55

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

That's it!

Upvotes: 0

Oliver
Oliver

Reputation: 503

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.

Upvotes: 4

Related Questions