【问题标题】:What is the difference between android.support.v4.app.fragment and androidx.fragment.app.FragmentActivityandroid.support.v4.app.fragment 和 androidx.fragment.app.FragmentActivity 有什么区别
【发布时间】:2020-02-01 12:28:32
【问题描述】:
当我尝试创建一个fragmentActivity时,import androidx.fragment.app.FragmentActivity下显然有一个X。但是,当我查找示例项目时,它会导入 android.support.v4.app.fragment。请问有什么区别,为什么我尝试运行自己的项目时会出现以下错误?:
java.lang.ClassCastException: com.fragmenttest.helloapp.ui.collection.ViewPagerIndicatorActivity cannot be cast to androidx.fragment.app.Fragment.
【问题讨论】:
标签:
java
android
android-fragments
android-support-library
androidx
【解决方案1】:
android.support.v4.app.fragment 是旧 Android 支持片段的包。
androidx.fragment.app.FragmentActivity 这是新片段所在的位置。这取代了以前的包,因为它是一个更干净的命名空间。这也称为 Android X。
您看到的示例可能是旧的并且仍然使用旧包。如果我没记错的话,Androidx 是在一两年前推出的。
在大多数情况下你可以简单地替换导入,但我认为最好的方法是使用 Android Studio 的migrate to Androidx
【解决方案2】:
首先,您使用的是不同的库。
android.support.v4.app.* 包含在支持库中。
androidx.fragment.app.* 包含在androidx libraries 中。
他们不能一起工作。检查信息到migrate。
那么Activity(或子类)不是Fragment。
您不能在 Activity 中投射片段。
【解决方案3】:
Activity != Fragment,您的java.lang.ClassCastException 建议您将Fragment 转换为Activity
Activity 是全屏(大部分),Fragment 只是一个外观,有点扩展View。一个Activity 可以处理多个Fragments,例如在bigger screens。
FragmentActivity 是在支持包中引入的,用于处理较低操作系统版本中的所有Fragments 功能,现在您应该使用AppCompatActivity 其中extends FragmentActivity