片段无法转换为androidx.fragment.app.Fragment

时间:2019-11-04 09:28:45

标签: android-fragments dagger-2 androidx android-architecture-navigation

我正在尝试使用Android导航组件从一个片段导航到另一个片段。

当我打电话

 itemView.findNavController().navigate(direction)

我收到此错误

java.lang.ClassCastException: MyFragment cannot be cast to androidx.fragment.app.Fragment
    at androidx.fragment.app.Fragment.instantiate(Fragment.java:523)
    at androidx.fragment.app.FragmentContainer.instantiate(FragmentContainer.java:57)
    at androidx.fragment.app.FragmentManagerImpl$6.instantiate(FragmentManagerImpl.java:2851)
    at androidx.navigation.fragment.FragmentNavigator.instantiateFragment(FragmentNavigator.java:132)
    at androidx.navigation.fragment.FragmentNavigator.navigate(FragmentNavigator.java:162)
    at androidx.navigation.fragment.FragmentNavigator.navigate(FragmentNavigator.java:58)
    at androidx.navigation.NavController.navigate(NavController.java:859)
    at androidx.navigation.NavController.navigate(NavController.java:793)
    at androidx.navigation.NavController.navigate(NavController.java:730)
    at androidx.navigation.NavController.navigate(NavController.java:716)
    at androidx.navigation.NavController.navigate(NavController.java:907)
    at MyViewHolder$bind$1.onClick(MyViewHolder.kt:31)
    at android.view.View.performClick(View.java:6663)
    at android.view.View.performClickInternal(View.java:6635)
    at android.view.View.access$3100(View.java:794)
    at android.view.View$PerformClick.run(View.java:26199)
    at android.os.Handler.handleCallback(Handler.java:907)
    at android.os.Handler.dispatchMessage(Handler.java:105)
    at android.os.Looper.loop(Looper.java:216)
    at android.app.ActivityThread.main(ActivityThread.java:7625)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)

我猜这是因为MyFragmentDaggerFragment,而DaggerFragmentandroid.support.v4.app.Fragment

但是我在gradle.properties中启用了Jetifier:

android.useAndroidX=true
android.enableJetifier=true

这不是应该将我的v4片段转换为androidx片段吗?

1 个答案:

答案 0 :(得分:0)

DaggerFragment已过时,所以我摆脱了它。

我将Dagger版本提高到2.23.2:

// Dagger
implementation "com.google.dagger:dagger:2.23.2"
kapt "com.google.dagger:dagger-compiler:2.23.2"

// Dagger Android
implementation "com.google.dagger:dagger-android:2.23.2"
implementation "com.google.dagger:dagger-android-support:2.23.2"
kapt "com.google.dagger:dagger-android-processor:2.23.2"

我的片段现在继承了 androidx 片段,而不是DaggerFragment。为了保持注入正常工作,我使用 AndroidSupportInjection

class MyFragment : Fragment()  {
    override fun onAttach(context: Context) {
        super.onAttach(context)
        AndroidSupportInjection.inject(this)
    }
}