Android 崩溃 onCreate() - Fragment 无法转换为 androidx.navigation.fragment.NavHostFragment

     2023-04-18     268

关键词:

【中文标题】Android 崩溃 onCreate() - Fragment 无法转换为 androidx.navigation.fragment.NavHostFragment【英文标题】:Android crash onCreate() - Fragment cannot be cast to androidx.navigation.fragment.NavHostFragment 【发布时间】:2020-12-29 01:17:45 【问题描述】:

我决定为我的应用执行 Firebase Robo 测试,发现它总是在打开外部 Activity 然后返回应用后崩溃。通过在开发者选项中启用“不保留活动”,我能够重现该问题。

崩溃:java.lang.ClassCastException: com.example.problemtesting.Fragments.Fragment_2 cannot be cast to androidx.navigation.fragment.NavHostFragment

说明问题是由这行代码引起的:NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment);

如何复制问题:

    启用“不保留活动” 打开应用,然后打开应用抽屉 选择“片段 2” 按下分享按钮 按下消息按钮(或任何其他外部应用程序) 返回应用(崩溃)

如果禁用“不保留活动”,该应用可以正常工作。

MainActivity

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener 

    DrawerLayout drawer;
    NavigationView navigationView;
    FragmentManager fragmentManager;
    AppBarConfiguration mAppBarConfiguration;
    NavController navController;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        fragmentManager = getSupportFragmentManager();
        drawer = findViewById(R.id.drawer_layout);
        navigationView = findViewById(R.id.nav_view);

        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        mAppBarConfiguration = new AppBarConfiguration.Builder(
                R.id.nav_fragment_1, R.id.nav_fragment_2)
                .setOpenableLayout(drawer)
                .build();

        NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment);
        if (navHostFragment != null)
            navController = navHostFragment.getNavController();
        else navController = Navigation.findNavController(this, R.id.nav_host_fragment);

        NavigationUI.setupActionBarWithNavController(MainActivity.this, navController, mAppBarConfiguration);
        NavigationUI.setupWithNavController(navigationView, navController);

        setNavigationViewListener();
    

    @Override
    public boolean onSupportNavigateUp() 
        return NavigationUI.navigateUp(navController, mAppBarConfiguration)
                || super.onSupportNavigateUp();
    

    private void setNavigationViewListener() 
        navigationView.setNavigationItemSelectedListener(MainActivity.this);
    

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) 
        switch (menuItem.getItemId()) 
            case R.id.nav_fragment_1: 
                fragmentManager.beginTransaction()
                        .replace(R.id.nav_host_fragment, new Fragment_1())
                        .commitNow();
                MainActivity.this.setTitle("Fragment 1");
                break;
            
            case R.id.nav_fragment_2: 
                fragmentManager.beginTransaction()
                        .replace(R.id.nav_host_fragment, new Fragment_2())
                        .commitNow();
                MainActivity.this.setTitle("Fragment 2");
                break;
            
        
        drawer.closeDrawers();
        return true;
    

片段 1

public class Fragment_1 extends Fragment

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) 

        container.removeAllViews();
        View root = inflater.inflate(R.layout.fragment_1, container, false);

        return root;
    

片段 2

public class Fragment_2 extends Fragment 

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) 

        container.removeAllViews();
        View root = inflater.inflate(R.layout.fragment_2, container, false);

        Button share = root.findViewById(R.id.share);

        share.setOnClickListener(view -> 
            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.setType("text/plain");
            intent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
            intent.putExtra(Intent.EXTRA_TEXT, "Message");
            startActivity(Intent.createChooser(intent, "Title"));
        );

        return root;
    

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_
    android:layout_
    android:fitsSystemWindows="true"
    tools:openDrawer="start"
    >

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:tag="my_fragment"
        android:layout_
        android:layout_
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:defaultNavHost="true"
        app:navGraph="@navigation/mobile_navigation"
        />

    <com.google.android.material.navigation.NavigationView
        android:id="@+id/nav_view"
        android:layout_
        android:layout_
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/main_drawer"
        />
</androidx.drawerlayout.widget.DrawerLayout>

mobile_navigation.xml

<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    app:startDestination="@+id/nav_fragment_1">

    <fragment
        android:id="@+id/nav_fragment_1"
        android:name="com.example.problemtesting.Fragments.Fragment_1"
        tools:layout="@layout/fragment_1"
        />
    <fragment
        android:id="@+id/nav_fragment_2"
        android:name="com.example.problemtesting.Fragments.Fragment_2"
        tools:layout="@layout/fragment_2"
        />
</navigation>

ma​​in_drawer.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:showIn="navigation_view">

    <group android:checkableBehavior="single">
        <item
            android:id="@+id/nav_fragment_1"
            android:title="Fragment 1" />
        <item
            android:id="@+id/nav_fragment_2"
            android:title="Fragment 2" />
    </group>
</menu>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.problemtesting">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name="com.example.problemtesting.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

这是一个令人沮丧的问题,我无法弄清楚。我已尝试删除 NavigationView.OnNavigationItemSelectedListener 侦听器,它工作正常,但我需要该侦听器用于其他控件,例如片段切换动画和抽屉布局转换。

【问题讨论】:

【参考方案1】:

问题是您的onNavigationItemSelected 正在执行FragmentTransaction,用片段替换整个NavHostFragment。使用NavHostFragment 时,这始终是更改片段的错误方法 - 您应该始终使用navigating to a destination。

但是,就您而言,您所做的工作比实际需要的要多。相反,您应该:

    完全删除您的OnNavigationItemSelectedListener 代码。当您致电 NavigationUI.setupWithNavController(navigationView, navController); 时,导航已经为您设置了一个,包括关闭抽屉并根据 Material design 规范使用正确的淡入淡出动画。

    根据top app bar guide,您应该手动设置活动的标题,而是将android:label 添加到图表中的每个目的地,然后setupActionBarWithNavController 呼叫您'已经为您完成了。

【讨论】:

感谢您的澄清。我采用这种方法的原因是有更多的控制权。一些太大的碎片导致抽屉在关闭时结结巴巴。我制作了一个将在 300 毫秒后触发的处理程序,然后切换片段以避免口吃。我不确定如何在没有 OnNavigationItemSelectedListener 的情况下实现这一点。 听起来你应该为this existing issue 加注星标。 default onNavigationItemSelected() 调用 NavigationUI.onNavDestinationSelected() 所以调用它来保持行为 谢谢!我刚刚尝试了 NavigationUI.onNavDestinationSelected(),它适用于我现有的代码。 NavHostFragment 错误也不再有问题。 这正是我的应用程序在屏幕旋转时崩溃的原因。新的导航控制器似乎不适用于过渡到片段的旧方法,并且必须使用导航控制器完成过渡。非常感谢这有帮助。 @MihaM 请问你的 onNavigationItemSelected() 的新代码是什么?

Android 崩溃 onCreate() - Fragment 无法转换为 androidx.navigation.fragment.NavHostFragment

】Android崩溃onCreate()-Fragment无法转换为androidx.navigation.fragment.NavHostFragment【英文标题】:AndroidcrashonCreate()-Fragmentcannotbecasttoandroidx.navigation.fragment.NavHostFragment【发布时间】:2020-12-2901:17:45【问题描述】:我决定为我的应用执行Fire 查看详情

mapView.onCreate 在 api 级别 26 的cordova android 应用程序中工作正常,但在 api 级别 28 时崩溃

】mapView.onCreate在api级别26的cordovaandroid应用程序中工作正常,但在api级别28时崩溃【英文标题】:mapView.onCreateworksfineincordovaandroidappwithapilevel26,butcrasheswithapilevel28【发布时间】:2021-05-1222:19:16【问题描述】:我有一个使用mapkit插件... 查看详情

Android资源未找到异常oncreate

】Android资源未找到异常oncreate【英文标题】:Androidresourcenotfoundexceptiononcreate【发布时间】:2019-03-0220:25:04【问题描述】:所以我创建了我的应用程序,它在我测试的手机上运行良好,但错误提示告诉我它正在为其他用户崩溃。... 查看详情

Android 整理 Intent 调用父级的 onCreate()

】Android整理Intent调用父级的onCreate()【英文标题】:AndroidfinishingIntentcallsonCreate()ofparent【发布时间】:2021-09-0818:39:33【问题描述】:我遇到了由于NullPointerException而导致我的应用程序不断崩溃的问题。由于缺少值,无法进行数据... 查看详情

Android WebView loadURL 崩溃的应用程序? [复制]

】AndroidWebViewloadURL崩溃的应用程序?[复制]【英文标题】:AndroidWebViewloadURLcrashingapp?[duplicate]【发布时间】:2014-07-0410:23:03【问题描述】:我有这个代码:protectedvoidonCreate(BundlesavedInstanceState)super.onCreate(savedInstanceState);setContentView 查看详情

如何获得android的崩溃日志

...server构成.应用启动时,会首先启动Application.在Application的onCreate方法中调用1Thread.setDefaultUncaughtExceptionHandler(handler); 就可以捕获导致应用崩溃的错误信息了.首先应用要有读写sd卡权限系统错误后要还是要提示用户系统错误.这个... 查看详情

崩溃时自动重启 android mono 应用程序

...选项有疑问。我实现这个请求的想法如下,在MainLauncher的OnCreate函数中创建一个PendingIntent。在这种情况下,这个PendingInt 查看详情

Android 5.0.x 上的应用程序崩溃

】Android5.0.x上的应用程序崩溃【英文标题】:appcrashonAndroid5.0.x【发布时间】:2015-06-1908:55:42【问题描述】:我在android版本5.0.X上遇到应用程序崩溃的问题。没有错误可用,只有这个警告:06-1911:50:22.900:W/google-breakpad(24934):Chromebuil... 查看详情

android google map v2 在 gmap lstarts 上不断崩溃

...视图v2在启动时不断崩溃,这段代码有什么问题protectedvoidonCreate(BundlesavedInstanceState)super.onCreate(savedInsta 查看详情

androidopengl表面崩溃在设备方向改变问题,怎么解决

...entView中,这样它将会填充你的整个手机屏幕。Activity中的onCreate方法如下:protectedvoidonCreate(BundlesavedInstanceState)super.onCreate(savedInstanceState);GLSurfaceViewview=newGLSurfaceView(this);setContentView(view);123456123456因为媒体效果的框架仅仅支持OpenG 查看详情

什么是android中的OnCreate方法

】什么是android中的OnCreate方法【英文标题】:WhatisaOnCreatemethodinandroid【发布时间】:2013-11-0113:39:45【问题描述】:我是android新手,试图了解以下方法的作用publicvoidonCreate(BundlesavedInstanceState)super.onCreate(savedInstanceState);//loadthelayouts... 查看详情

android的fragment知识点

...考技术Afrgment被创建的时候,相关的生命周期,onAttach(),onCreate(),onCreateView(),onActivityCreated();fragment对用户可见的时候,相关的生命周期,onStrat(),onResume(),fragment进入“后台模式”的时候,相关的生命周期,onPause(),onStop(),fragment被销... 查看详情

Android 11 onCreate() 调用每秒钟都丢失

】Android11onCreate()调用每秒钟都丢失【英文标题】:Android11onCreate()callismissingeverysecondtime【发布时间】:2021-01-2107:53:50【问题描述】:在Android11上运行时,一个成熟的应用突然出现了前所未有的生命周期问题:开始调试onCreate()被... 查看详情

Android - 活动构造函数与 onCreate

】Android-活动构造函数与onCreate【英文标题】:Android-ActivityConstructorvsonCreate【发布时间】:2011-03-1903:31:51【问题描述】:我了解AndroidActivities具有特定的生命周期,应该重写onCreate并用于初始化,但构造函数中究竟发生了什么?是... 查看详情

在 onCreate() 之前,Android 系统服务不可用于活动 [关闭]

】在onCreate()之前,Android系统服务不可用于活动[关闭]【英文标题】:AndroidSystemservicesnotavailabletoActivitiesbeforeonCreate()[closed]【发布时间】:2013-01-2800:23:08【问题描述】:....@OverrideprotectedvoidonCreate(BundlesavedInstanceState)super.onCreate(s 查看详情

如何在 onCreate 方法中设置 android 按钮的文本?

】如何在onCreate方法中设置android按钮的文本?【英文标题】:HowtosettextofandroidbuttoninonCreateMethod?【发布时间】:2021-04-0503:06:43【问题描述】:我想在onCreate方法中设置我的按钮的文本,但它不起作用。MainActivity-Class中的代码:Butto... 查看详情

Android 聊天在 DataSnapshot.getValue() 上崩溃以获取时间戳

】Android聊天在DataSnapshot.getValue()上崩溃以获取时间戳【英文标题】:AndroidchatcrashesonDataSnapshot.getValue()fortimestamp【发布时间】:2014-10-1910:38:32【问题描述】:我正在尝试修改Firebase的Android聊天示例以包含Firebase时间戳值。我可以使... 查看详情

自定义 android.app.Application 未触发 onCreate 事件

】自定义android.app.Application未触发onCreate事件【英文标题】:customandroid.app.ApplicationnotfiringonCreateevent【发布时间】:2011-10-1501:10:14【问题描述】:我正在从android.app.Application派生一个自定义应用程序,但我无法触发它的onCreate事件... 查看详情