【问题标题】:ClassNotFoundException when using androidx.fragment.app.FragmentContainerView使用 androidx.fragment.app.FragmentContainerView 时出现 ClassNotFoundException
【发布时间】:2020-05-17 10:52:00
【问题描述】:

我正在尝试从使用FrameLayout 过渡到使用FragmentContainerView,从我看过的教程来看,这应该很容易。但是,当我在进行更改后运行我的应用程序时,我得到了

Error inflating class androidx.fragment.app.FragmentContainerView
Caused by: java.lang.ClassNotFoundException: androidx.fragment.app.FragmentContainerView

我的布局文件非常简单:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:tools="http://schemas.android.com/tools"
tools:showIn="@layout/app_bar_main">

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/fragment_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>

我需要在我的 build.gradle 中添加一些东西吗?为什么找不到类?

【问题讨论】:

标签: android android-fragments


【解决方案1】:

androidx.fragment 1.2.0 或更高版本:

implementation "androidx.fragment:fragment:1.2.0"

【讨论】:

  • 谢谢!我想我需要这样的声明,只是找不到任何关于如何格式化的文档
  • 相同。很遗憾我不得不用谷歌搜索。
  • 对于 kotlin 实现 'androidx.fragment:fragment-ktx:1.4.0'
【解决方案2】:

感谢@Salam El-Banna 和他的link,我发现如果应用程序在release 构建中崩溃,我们应该添加proguard-rules.pro(一两行,取决于&lt;FragmentContainerView&gt; 中的android:name

#-------------------------------------------------
# JetPack Navigation
# This fixes: 
# Caused by: androidx.fragment.app.Fragment$InstantiationException: Unable to instantiate fragment androidx.navigation.fragment.NavHostFragment: make sure class name exists
# Caused by: androidx.fragment.app.Fragment$InstantiationException: Unable to instantiate fragment com.google.android.gms.maps.SupportMapFragment: make sure class name exists
#-------------------------------------------------

-keepnames class androidx.navigation.fragment.NavHostFragment
-keepnames class com.google.android.gms.maps.SupportMapFragment

【讨论】:

    【解决方案3】:

    确保它们不是这样的自定义构造函数。
    例如:

    FragmentName (val ctx: Context): Fragment() {
    

    改为

    FragmentName: Fragment() {
    

    原因是inflater在对FrgmentContainer进行膨胀时,会调用默认构造函数来初始化片段。如果它们没有可用的默认构造函数,它将崩溃。

    【讨论】:

      【解决方案4】:

      如果您使用的是 kotlin,则最新的 FragmentContainerView 实现保留在:

      implementation("androidx.fragment:fragment-ktx:1.3.6")
      

      【讨论】:

        猜你喜欢
        • 2013-03-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多