Android: Preference Fragment with a Navigation Drawer's Fragment

北城以北 提交于 2019-11-28 11:18:59

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

In Activity use this code to add 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 be 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() 
  {

  }
}

Wrap your current PreferenceFragment with a simple Fragment which does noting but opens 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);
       }     
     }
}

How about this:

Fragment preferenceFragment = new SettingsFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(android.R.id.content, preferenceFragment);
ft.commit();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!