Android: Preferences fragment with navigation box fragment

Hi, I have an Android app that already uses a navigation box. My MainActivity extends the action of the fragments , and my SettingFragment parameter extends the PreferenceFragment

Settings snippet :

public class SettingsFragment extends PreferenceFragment { public SettingsFragment() {} @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Load the preferences from an XML resource addPreferencesFromResource(R.xml.prefs); } } 

and my MainActivity :

 PreferenceFragment preferenceFragment = new SettingsFragment(); FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.add(android.R.id.content, preferenceFragment); // I'm getting an error here should be Fragment not PreferenceFragment ft.commit(); 

How can I commit or go to SettingsFragment ()?

+8
android android-fragments android-preferences navigation-drawer
source share
3 answers

This worked for me. Just keep in mind that this code will work with api leval 11 and above.

In the operation, use this code to add a fragment.

 android.app.Fragment infoFragment = new InfoFragment(); FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.add(android.R.id.content, infoFragment); ft.commit(); 

And your PreferenceFragment class will look like this.

 public class InfoFragment extends PreferenceFragment { /** * The fragment argument representing the section number for this * fragment. */ private static final String ARG_SECTION_NUMBER = "section_number"; /** * Returns a new instance of this fragment for the given section * number. */ public static android.app.Fragment newInstance(int sectionNumber) { InfoFragment fragment = new InfoFragment(); Bundle args = new Bundle(); args.putInt(ARG_SECTION_NUMBER, sectionNumber); fragment.setArguments(args); return fragment; } public InfoFragment() { } } 
+2
source share

Wrap your current PreferenceFragment with a simple snippet that marks but opens the prefenceFragment as follows

 public class SettingsActivity extends Fragment { @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); getActivity().getFragmentManager().beginTransaction() .replace(android.R.id.content, new MyPreferenceFragment()) .commit(); } private class SettingsFragment extends PreferenceFragment { public SettingsFragment() {} @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Load the preferences from an XML resource addPreferencesFromResource(R.xml.prefs); } } } 
+12
source share

How about this:

 Fragment preferenceFragment = new SettingsFragment(); FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.add(android.R.id.content, preferenceFragment); ft.commit(); 
0
source share

All Articles