apparently there is a X
under import androidx.fragment.app.FragmentActivity
, when I try to create a fragmentActivity. However, when I look for a sample project, it imports android.support.v4.app.fragment
instead. May I know whats the difference, and why do I have this following error when I try to run my own project?:
java.lang.ClassCastException: com.fragmenttest.helloapp.ui.collection.ViewPagerIndicatorActivity cannot be cast to androidx.fragment.app.Fragment.
android.support.v4.app.fragment
it's the package for the old Android support fragments.
androidx.fragment.app.FragmentActivity
it's where the new fragments are. This came to replace the previous package because it's a much cleaner namespace. This is also known as Android X.
Probably the examples you're seeing are old and still use the old package. If I'm not mistaken Androidx was introduced 1 or 2 years ago.
In most cases you can simply replace the import, but I think the best way is to use Android Studio's migrate to Androidx
First of all you are using different libraries.
android.support.v4.app.*
is included in the support libraries .
androidx.fragment.app.*
is included in the androidx libraries .
They can't work together. Check the info to migrate .
Then an Activity
(or subclasses) is not a Fragment
.
You can't cast a Fragment in an Activity.
Activity
!= Fragment
, your java.lang.ClassCastException
is suggesting that you want to cast Fragment
to Activity
Activity
is full screen (mostly), Fragment
is only a piece of look, kind of very extended View
. One Activity
can handle multiple Fragment
s, eg on bigger screens .
FragmentActivity
was introduced in support pack for handling all Fragment
s features in lower OS versions, now you should use AppCompatActivity
which extends FragmentActivity
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.