首页 > 解决方案 > 尝试使用 NavHostFragment 时出现错误:Error inflating class androidx.fragment.app.FragmentContainerView

问题描述

这是由以下原因引起的:“引起:android.view.InflateException:com.example.dnaire:layout/main 中的二进制 XML 文件第 21 行:com.example.dnaire:layout/main 中的二进制 XML 文件第 21 行:错误膨胀类 androidx.fragment.app.FragmentContainerView 导致:android.view.InflateException:com.example.dnaire:layout/main 中的二进制 XML 文件第 21 行:错误膨胀类 androidx.fragment.app.FragmentContainerView 导致:java .lang.reflect.InvocationTargetException"

我在项目中还没有太多代码,刚刚开始。

这是主要活动:

class Main : Activity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val mainBinding = MainBinding.inflate(layoutInflater)
        setContentView(mainBinding.root)
    }
}

这是包含导致问题的 FragmentContainerView 的 main.xml 文件:

<?xml version="1.0" encoding="utf-8"?>
<layout 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">
    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".Main">

        <androidx.fragment.app.FragmentContainerView
            android:id="@+id/nav_host_fragment"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="0dp"
            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/nav_graph" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

那是 nav_graph.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"
    android:id="@+id/nav_graph"
    app:startDestination="@id/startFragment">

    <fragment
        android:id="@+id/startFragment"
        android:name="com.example.dnaire.login.StartFragment"
        android:label="fragment_start"
        tools:layout="@layout/fragment_start" />
</navigation>

标签: androidkotlinnavigationnav

解决方案


您的活动必须是FragmentActivity使用androidx.fragment.app.FragmentContainerView您扩展的子类的子类FragmentActivityAppCompatActivityFragmentActivity类。建议延长AppCompatActivity.

jectpack 中 AppCompat 的 gradle 依赖项implementation 'androidx.appcompat:appcompat:1.2.0'


推荐阅读