Android应用程序在onCreate()方法中崩溃 - Fragment无法转换为androidx.navigation.fragment.NavHostFragment。

8
我决定对我的应用程序执行Firebase Robo测试,发现当打开外部活动然后返回到应用程序时,它总是崩溃。通过在开发者选项中启用“不保留活动”来复制问题。
崩溃: java.lang.ClassCastException: com.example.problemtesting.Fragments.Fragment_2 无法强制转换为 androidx.navigation.fragment.NavHostFragment 这表明问题是由以下代码行引起的:NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment); 如何复制问题:
  1. 启用“不保留活动”
  2. 打开应用程序然后打开应用程序抽屉
  3. 选择“片段2”
  4. 按分享按钮
  5. 按消息按钮(或任何其他外部应用)
  6. 返回应用程序(崩溃)
如果禁用“不保留活动”,该应用程序将正常工作。 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_width="match_parent"
    android:layout_height="match_parent"
    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_width="match_parent"
        android:layout_height="0dp"
        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_width="wrap_content"
        android:layout_height="match_parent"
        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>

main_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个回答

3
问题在于你的onNavigationItemSelected使用了FragmentTransaction,用一个Fragment替换了整个NavHostFragment。这总是不正确的方式,在使用NavHostFragment时更改片段应该始终是导航到目的地
但是,在你的情况下,你所做的工作远远超出了实际需要的范围。相反,你应该:
  1. 完全删除你的 OnNavigationItemSelectedListener 代码。当你调用 NavigationUI.setupWithNavController(navigationView, navController); 的时候,导航已经为你设置了一个。这包括关闭抽屉和根据Material设计规范使用正确的交叉淡入淡出动画。

  2. 根据顶部应用程序栏指南,你不应该手动设置活动标题,而是应该在图形中的每个目标中添加android:label,你已经调用的setupActionBarWithNavController将为你完成此操作。


感谢您的澄清。我选择这种方法的原因是为了更好地控制。一些太大的片段会导致抽屉关闭时出现卡顿。我已经创建了一个处理程序,在300毫秒后触发,然后切换片段以避免卡顿。我不确定如何在没有OnNavigationItemSelectedListener的情况下实现这一点。 - Miha M
1
听起来你应该给这个已存在的问题点赞。默认的onNavigationItemSelected()调用NavigationUI.onNavDestinationSelected(),所以调用它以保持行为一致。 - ianhanniballake
谢谢!我刚刚尝试了NavigationUI.onNavDestinationSelected(),并且它与我的现有代码非常配合。而且,再也没有关于NavHostFragment的错误问题了。 - Miha M
这正是我的应用程序在屏幕旋转时崩溃的原因。新的导航控制器似乎不能与旧的片段过渡方法一起使用,必须使用导航控制器进行过渡。非常感谢,这很有帮助。 - Amir Dora.
1
@MihaM,请问你的onNavigationItemSelected()的新代码是什么? - Fayçal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接