Search code examples
androidandroid-fragmentsbackwards-compatibility

Android: Workaround for support.v4.app.Fragment -> Fragment classcastexception?


I'm trying to add a support.v4.app.Fragment to a PreferenceActivity header, like so:

<header
    android:fragment="com.example.SupportFragmentSubClass"
    android:title="Selecting this should show the accompanying fragment" >
</header>

This throws a ClassCastException, presumably because the PreferenceActivity is expecting a sub-class of android.app.Fragment, rather than support.v4.app.Fragment.

My use case is this:
I have non-standard Fragment that I want to use as a preference on both <3.0 and >3.0 devices. For >=3.0, I need an android.app.Fragment subclass so it can be embedded in the 'detail pane' of the preferences activity on tablet devices. For <3.0, I need a v4.support.app.Fragment subclass so I can throw in it an ActivityFragment.

Is there a workaround that would allow me to use a compatibility Fragment in this situation?


Solution

  • PreferenceFragment is not in the Android Support package, and you cannot use an Android Support package Fragment class in a PreferenceActivity this way. Moreover, your headers would not work on Android 2.x anyway, since the PreferenceActivity in Android 2.x does not know about fragments.

    In principle, you could fork the PreferenceActivity from the source code to create one that does use the Android Support version of Fragment.

    Or, organize your preferences to use fragments on Android 3.0+ and avoid them on Android 2.x. Here is a sample project where I demonstrate a way to do this.