Nir Ben-Or
Nir Ben-Or

Reputation: 56

PreferenceFragment can't load from XML (ClassCastException)

I'm having some difficulties getting a PreferenceFragment to load using XML. It keeps throwing a ClassCastException "PreferenceFragmentClass cannot be cast to android.support.v4.app.Fragment". The code is intended to run on API14 and higher.

Here's my code:

import android.os.Bundle;
import android.preference.PreferenceFragment;

public class SettingsFragment extends PreferenceFragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.settings);

    }   
}

Here's the code where SettingsFragment is being used in:

import android.app.ActionBar;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;

public class FragmentsSetup extends FragmentActivity {

    private ViewPager viewPager;
    private TabsAdapter tabsAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        viewPager = new ViewPager(this);
        viewPager.setId(R.id.pager);
        setContentView(viewPager);

        final ActionBar actionBar = getActionBar();
        actionBar.setDisplayShowTitleEnabled(false);
        actionBar.setDisplayShowHomeEnabled(false);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        tabsAdapter = new TabsAdapter(this, viewPager);
        tabsAdapter.addTab(actionBar.newTab().setText(getString(R.string.forwarding_tab).toUpperCase()), ForwardingFragment.class, null);
        tabsAdapter.addTab(actionBar.newTab().setText(getString(R.string.settings_tab).toUpperCase()), SettingsFragment.class, null);
    }
}                        

Any tips would be greatly appreciated.

Upvotes: 0

Views: 577

Answers (2)

Benjamin Roberts
Benjamin Roberts

Reputation: 566

If you're developing for Android 3.0 (API level 11) and higher, you should use a PreferenceFragment to display your list of Preference objects. Also you can add a PreferenceFragment to any activity—you don't need to use PreferenceActivity.

See documentation here: https://developer.android.com/guide/topics/ui/settings.html?

Upvotes: 0

CommonsWare
CommonsWare

Reputation: 1006604

SettingsFragment inherits from PreferenceFragment. PreferenceFragment is from the native API Level 11 implementation of fragments. However, FragmentsSetup is inheriting from FragmentActivity, from the Android Support package's backport of fragments.

That combination will not work.

If you intend to support devices older than API Level 11, you cannot use PreferenceFragment. Also, I am uncertain if PreferenceFragment works outside of a PreferenceActivity (it might, but I have never tried that).

Upvotes: 2

Related Questions