Search code examples
androidandroid-fragmentspreferencefragment

Create Class to instantiate PreferenceFragment


I have an app with fragments. I’m having trouble getting the PreferenceFragment to work.One of the fragments is a settings page. For this I wish to use PreferenceFragment however I have developed my app using android.support.v4.app.FragmentManager which is not compatible with PreferenceFragment. The link below has a description and link to code that will work with v4.

https://github.com/codepath/android_guides/wiki/Settings-with-PreferenceFragment

https://github.com/kolavar/android-support-v4-preferencefragment

My MainActivity

private class CustomAdapter extends FragmentPagerAdapter {

private String fragments [] = {"Event","Gallery","Match","Settings"};

public CustomAdapter(FragmentManager supportFragmentManager, Context applicationContext) {
    super(supportFragmentManager);
}

@Override
public Fragment getItem(int position) {
    switch (position){
        case 0:
            return new event();
        case 1:
            return new gallery();
        case 2:
            return new match();
        case 3:
            return new PreferenceFragment();
        default:
            return null;
    }
}

error: 'PreferenceFragment' is abstract, cannot be instantiated.

PreferenceFragment

public abstract class PreferenceFragment extends Fragment implements
        PreferenceManagerCompat.OnPreferenceTreeClickListener {

    private static final String PREFERENCES_TAG = "android:preferences";

I’m told I can't instantiate a PreferenceFragment directly, I have to create a class that extends it. Could someone explain how I would go about doing that in this case? Thanks a million! :-)


Solution

  • For example:

    public class MyPreferenceFragment extends PreferenceFragment
    {
        @Override
        public void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.fragment_preference);
        }
    }
    

    And its associated XML file:

    <?xml version="1.0" encoding="utf-8"?>
    
    <PreferenceScreen
        xmlns:android="http://schemas.android.com/apk/res/android">
    
        <PreferenceCategory 
            android:title="FOO">
    
            <CheckBoxPreference
                android:key="checkBoxPref"
                android:title="check it out"
                android:summary="click this little box"/>
    
        </PreferenceCategory>
    
    </PreferenceScreen>
    

    Source: How do you create Preference Activity and Preference Fragment on Android?