简体   繁体   中英

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

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.

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

That's it!

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