0

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! :-)

MarcusRey
  • 373
  • 1
  • 2
  • 12

1 Answers1

2

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?

Community
  • 1
  • 1
frogatto
  • 28,539
  • 11
  • 83
  • 129
  • Thank you! I had actually got that far earlier but the settings page was showing as blank when I ran the app. I looked at the fragment_preference.xml and It was missing the tags. It had Tags which didn't work. Thanks a million for your help! :-) – MarcusRey Jan 19 '16 at 15:41