Why are there two Fragment classes in Android? [du

2019-08-29 20:21发布

问题:

This question already has an answer here:

  • Difference between android.app.Fragment and android.support.v4.app.Fragment 6 answers

In a recent question, the OP received an unexpected error message due to importing Fragment from the android.app package. The solution to fix the error was to import android.support.v4.app.Fragment instead. Why are there two different Fragment classes that appear to have the same functionality?

回答1:

According to the documentation, fragments were introduced in Android 3.0 (API 11). Around the same time, Google also released the Android Support Library which allowed developers to use fragments and other new APIs on devices that ran older versions of Android. This library contained classes with the exact same functionality as classes that shipped with the Android API on newer devices. Since these libraries can be compiled directly into your APK file, you no longer have to rely on the features being available on the target device. Some classes are now only available from the Support Library and rely on the support Fragment from this library rather than using the native Fragment class even though it is available on basically all devices now in use.