美文网首页
FragmentContainerView中的问题与解决方法

FragmentContainerView中的问题与解决方法

作者: 普通路人 | 来源:发表于2021-12-08 15:08 被阅读0次

    FragmentContainerView中的问题与解决方法

    一、发现问题

    1、错误表现

    今天在做一个项目的时候, 发现了一个莫名奇妙的问题。根据官方的建议,使用FragmentContainerView去切换和处理Fragment。

    为布局文件中的FragmentContainerView设置一个开始Fragment,我称之为FragmentA,同时需要FragmentA传入参数进行初始化,然后问题出现了:编译通过,布局文件没有任何问题,运行时报错并退出应用,报错指出我的布局文件出问题,同时提示一个用到的参数为空。

    当场裂开,此外我注意到此前我的代码中FragmentA会被初始化两次,我注释掉那个提示为空的参数,一切豁然开朗。

    原来FragmentA被初始化了两次:第一次初始化是在setContentView的时候进行初始化,此时没有参数传入,导致参数为空,导致android.view.InflateException错误,再导致提示布局文件错误。

    我想尝试复现这个错误,并尝试解决这个问题。

    2、错误日志

    --------- beginning of crash
    2021-12-07 20:07:43.034 10842-10842/ink.ptlr.nodemusic E/AndroidRuntime: FATAL EXCEPTION: main
        Process: ink.ptlr.nodemusic, PID: 10842
        java.lang.RuntimeException: Unable to start activity ComponentInfo{ink.ptlr.nodemusic/ink.ptlr.nodemusic.activity.UtilsActivity}: android.view.InflateException: Binary XML file line #18 in ink.ptlr.nodemusic:layout/activity_utils: Binary XML file line #18 in ink.ptlr.nodemusic:layout/activity_utils: Error inflating class androidx.fragment.app.FragmentContainerView
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:4060)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4247)
            at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:91)
            at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:149)
            at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:103)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2613)
            at android.os.Handler.dispatchMessage(Handler.java:110)
            at android.os.Looper.loop(Looper.java:219)
            at android.app.ActivityThread.main(ActivityThread.java:8668)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1109)
         Caused by: android.view.InflateException: Binary XML file line #18 in ink.ptlr.nodemusic:layout/activity_utils: Binary XML file line #18 in ink.ptlr.nodemusic:layout/activity_utils: Error inflating class androidx.fragment.app.FragmentContainerView
         Caused by: android.view.InflateException: Binary XML file line #18 in ink.ptlr.nodemusic:layout/activity_utils: Error inflating class androidx.fragment.app.FragmentContainerView
         Caused by: java.lang.NullPointerException
            at ink.ptlr.nodemusic.fragment.MusicListFragment.onCreate(MusicListFragment.kt:46)
            at androidx.fragment.app.Fragment.performCreate(Fragment.java:2949)
            at androidx.fragment.app.FragmentStateManager.create(FragmentStateManager.java:475)
            at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:278)
            at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:2189)
            at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:2106)
            at androidx.fragment.app.FragmentManager.execSingleAction(FragmentManager.java:1971)
            at androidx.fragment.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:311)
            at androidx.fragment.app.FragmentContainerView.<init>(FragmentContainerView.java:180)
            at androidx.fragment.app.FragmentLayoutInflaterFactory.onCreateView(FragmentLayoutInflaterFactory.java:52)
            at androidx.fragment.app.FragmentController.onCreateView(FragmentController.java:135)
            at androidx.fragment.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:319)
            at androidx.fragment.app.FragmentActivity.onCreateView(FragmentActivity.java:298)
            at android.view.LayoutInflater.tryCreateView(LayoutInflater.java:1079)
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:1007)
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:971)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:1133)
            at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1094)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:692)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:536)
            at com.android.internal.policy.HwPhoneLayoutInflater.inflate(HwPhoneLayoutInflater.java:138)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:483)
            at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:699)
            at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:195)
            at ink.ptlr.nodemusic.activity.UtilsActivity.onCreate(UtilsActivity.kt:25)
            at android.app.Activity.performCreate(Activity.java:8214)
            at android.app.Activity.performCreate(Activity.java:8202)
    2021-12-07 20:07:43.034 10842-10842/ink.ptlr.nodemusic E/AndroidRuntime:     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1320)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:4033)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4247)
            at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:91)
            at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:149)
            at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:103)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2613)
            at android.os.Handler.dispatchMessage(Handler.java:110)
            at android.os.Looper.loop(Looper.java:219)
            at android.app.ActivityThread.main(ActivityThread.java:8668)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1109)
    2021-12-07 20:07:43.041 10842-10842/ink.ptlr.nodemusic I/Process: Sending signal. PID: 10842 SIG: 9
    

    二、问题复现

    1、创建项目

    新建一个名为FCVT(FragmentContainerViewTest)的项目,在下面新建一个MainActivity和一个TestFragment,采用FragmentContainerView
    结构如下:

    TCVT项目结构
    【提示】需要以下依赖:
    implementation 'androidx.fragment:fragment:1.3.2'
    

    MainActivity

    负责载入布局文件并初始化Fragment。

    • activity_main.xml
    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
        <!-- 动态加载Fragment -->
        <!-- 并设置起始Fragment为TestFragment -->
        <androidx.fragment.app.FragmentContainerView
            android:id="@+id/fragmentContainerView"
            android:name="ink.ptlr.fcvt.TestFragment"
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            tools:layout="@layout/test_fragment" />
    <!-- 报错会指向上一行,但实际上这个布局文件没有任何问题 -->
    </androidx.constraintlayout.widget.ConstraintLayout>
    
    • MainActyvity.kt
    package ink.ptlr.fcvt
    
    import androidx.appcompat.app.AppCompatActivity
    import android.os.Bundle
    
    class MainActivity : AppCompatActivity() {
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            /* 在这里被实例化一次
             * 此时,没有传入数据参数,为空,会导致报错
             */
            setContentView(R.layout.activity_main)
            val transaction = supportFragmentManager.beginTransaction()
            for(fragment in supportFragmentManager.fragments){
                transaction.remove(fragment)
            }
            // 第二次被初始化,可正常执行
            val fcvt: TestFragment = TestFragment.newInstance("Hello FCVT",1024)
            transaction.add(fcvt,"FCVT")
            transaction.commitNow()
        }
    }
    

    TestFragment

    • test_fragment.xml
    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".TestFragment">
        <!-- 用于显示信息 -->
        <TextView
            android:id="@+id/tvMsg"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:textAlignment="center"
            android:textSize="20sp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    
    • TestFragment.kt
    package ink.ptlr.fcvt
    
    import android.annotation.SuppressLint
    import androidx.lifecycle.ViewModelProvider
    import android.os.Bundle
    import android.util.Log
    import androidx.fragment.app.Fragment
    import android.view.LayoutInflater
    import android.view.View
    import android.view.ViewGroup
    import android.widget.TextView
    
    private const val KEY_MSG = "MSG"
    private const val KEY_NUM = "NUM"
    // private var count = 1
    class TestFragment : Fragment() {
        companion object {
            /*这里传入参数*/
            fun newInstance(msg: String, num: Int) = TestFragment().apply {
                arguments = Bundle().apply {
                    putString(KEY_MSG,msg)
                    putInt(KEY_NUM, num)
                }
            }
        }
        private lateinit var viewModel: TestViewModel
        private var msg: String? = null
        private var num: Int? = null
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            /*获取参数*/
            arguments?.let {
                msg = it.getString(KEY_MSG)
                num = it.getInt(KEY_NUM)
            }
            /*此时不能使用参数num,否则会报错*/
            var result = num!!.plus(1)
            Log.i("FCVT","MSG: $msg, NUM: ${num}")
            //count++
        }
        @SuppressLint("SetTextI18n")
        override fun onCreateView(
            inflater: LayoutInflater, container: ViewGroup?,
            savedInstanceState: Bundle?
        ): View? {
            val rootView:View = inflater.inflate(R.layout.test_fragment, container, false)
            val tvMsg: TextView = rootView.findViewById(R.id.tvMsg)
            tvMsg.text = "MSG: $msg, NUM: $num"
            return rootView
        }
        override fun onActivityCreated(savedInstanceState: Bundle?) {
            super.onActivityCreated(savedInstanceState)
            viewModel = ViewModelProvider(this).get(TestViewModel::class.java)
            // TODO: Use the ViewModel
        }
    }
    

    2、编译运行于报错

    上面的代码可以通过编译,但运行时应用闪退,报错日志如下:

     --------- beginning of crash
    2021-12-08 12:48:10.344 31676-31676/? E/AndroidRuntime: FATAL EXCEPTION: main
        Process: ink.ptlr.fcvt, PID: 31676
        java.lang.RuntimeException: Unable to start activity ComponentInfo{ink.ptlr.fcvt/ink.ptlr.fcvt.MainActivity}: android.view.InflateException: Binary XML file line #19 in ink.ptlr.fcvt:layout/activity_main: Binary XML file line #19 in ink.ptlr.fcvt:layout/activity_main: Error inflating class androidx.fragment.app.FragmentContainerView
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:4060)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4247)
            at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:91)
            at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:149)
            at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:103)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2613)
            at android.os.Handler.dispatchMessage(Handler.java:110)
            at android.os.Looper.loop(Looper.java:219)
            at android.app.ActivityThread.main(ActivityThread.java:8668)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1109)
         Caused by: android.view.InflateException: Binary XML file line #19 in ink.ptlr.fcvt:layout/activity_main: Binary XML file line #19 in ink.ptlr.fcvt:layout/activity_main: Error inflating class androidx.fragment.app.FragmentContainerView
         Caused by: android.view.InflateException: Binary XML file line #19 in ink.ptlr.fcvt:layout/activity_main: Error inflating class androidx.fragment.app.FragmentContainerView
         Caused by: java.lang.NullPointerException
            at ink.ptlr.fcvt.TestFragment.onCreate(TestFragment.kt:39)
            at androidx.fragment.app.Fragment.performCreate(Fragment.java:2949)
            at androidx.fragment.app.FragmentStateManager.create(FragmentStateManager.java:475)
            at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:278)
            at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:2189)
            at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:2106)
            at androidx.fragment.app.FragmentManager.execSingleAction(FragmentManager.java:1971)
            at androidx.fragment.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:311)
            at androidx.fragment.app.FragmentContainerView.<init>(FragmentContainerView.java:176)
            at androidx.fragment.app.FragmentLayoutInflaterFactory.onCreateView(FragmentLayoutInflaterFactory.java:52)
            at androidx.fragment.app.FragmentController.onCreateView(FragmentController.java:135)
            at androidx.fragment.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:319)
            at androidx.fragment.app.FragmentActivity.onCreateView(FragmentActivity.java:298)
            at android.view.LayoutInflater.tryCreateView(LayoutInflater.java:1079)
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:1007)
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:971)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:1133)
            at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1094)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:692)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:536)
            at com.android.internal.policy.HwPhoneLayoutInflater.inflate(HwPhoneLayoutInflater.java:138)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:483)
            at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:696)
            at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:170)
            at ink.ptlr.fcvt.MainActivity.onCreate(MainActivity.kt:12)
            at android.app.Activity.performCreate(Activity.java:8214)
            at android.app.Activity.performCreate(Activity.java:8202)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1320)
    2021-12-08 12:48:10.344 31676-31676/? E/AndroidRuntime:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:4033)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4247)
            at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:91)
            at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:149)
            at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:103)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2613)
            at android.os.Handler.dispatchMessage(Handler.java:110)
            at android.os.Looper.loop(Looper.java:219)
            at android.app.ActivityThread.main(ActivityThread.java:8668)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1109)
    
    

    三、错误分析

    这个问题困扰了我佷久,因为出现了不止一次,而且每次都困扰了我很久。
    仔细分析后发现了问题所在:
    setContentView时TestFragment会被实例化,此时需要自定义的参数是没有初始化的,不能使用。
    在代码中:

    /*此时不能使用参数num,否则会报错*/
    var result = num!!.plus(1)
    

    我使用!!告诉编译器这个数据不为空,于是编译通过,但实际情况是这个数据会出现为空的情况,于是在运行的时候出现了错误。
    错误的原因:在上述项目中,TesTFragment会被初始化两次,第一次是setContentView的时候,第二次是调用TestFragment.instance(msg: String, num: Int)的时候。

    四、解决方法

    思路:在创建时传入参数或只实例化一次
    需求不能变,在初始化时传入参数是要求,在仔细阅读官方文档Fragment 管理器 | Android 开发者 | Android Developers (google.cn)后,通过自定义FragmentFactory解决问题(创建时传入参数)。
    修改后:
    TestFragment.kt

    package ink.ptlr.fcvt
    
    import android.annotation.SuppressLint
    import androidx.lifecycle.ViewModelProvider
    import android.os.Bundle
    import android.util.Log
    import androidx.fragment.app.Fragment
    import android.view.LayoutInflater
    import android.view.View
    import android.view.ViewGroup
    import android.widget.TextView
    import androidx.fragment.app.FragmentFactory
    
    private const val KEY_MSG = "MSG"
    private const val KEY_NUM = "NUM"
    // private var count = 1
    class TestFragment() : Fragment() {
        companion object {
            /*这里传入参数*/
            fun newInstance(msg: String, num: Int) = TestFragment().apply {
                arguments = Bundle().apply {
                    putString(KEY_MSG,msg)
                    putInt(KEY_NUM, num)
                }
            }
        }
        private lateinit var viewModel: TestViewModel
        private var msg: String? = null
        private var num: Int? = null
        init {
            msg = "Init By default"
        }
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            /*获取参数*/
            arguments?.let {
                msg = it.getString(KEY_MSG)
                num = it.getInt(KEY_NUM)
            }
            /*此时不能使用参数num,否则会报错*/
            //var result = num!!.plus(1)
            Log.i("FCVT","MSG: $msg, NUM: ${num}")
            //count++
        }
        @SuppressLint("SetTextI18n")
        override fun onCreateView(
            inflater: LayoutInflater, container: ViewGroup?,
            savedInstanceState: Bundle?
        ): View? {
            Log.i("FCVT","OCV")
            var rootView:View = inflater.inflate(R.layout.test_fragment, container, false)
            val tvMsg: TextView = rootView.findViewById(R.id.tvMsg)
            tvMsg.text = "MSG: $msg, NUM: $num"
            return rootView
        }
    
        override fun onActivityCreated(savedInstanceState: Bundle?) {
            super.onActivityCreated(savedInstanceState)
            viewModel = ViewModelProvider(this).get(TestViewModel::class.java)
            // TODO: Use the ViewModel
        }
        // 自定义的FragmentFactory,内部类
        class MyFactory(var msg: String, var num: Int): FragmentFactory(){
            override fun instantiate(classLoader: ClassLoader, className: String): Fragment =
                when(loadFragmentClass(classLoader, className)){
                    TestFragment::class.java -> newInstance(msg, num)
                    else -> super.instantiate(classLoader, className)
                }
    
        }
    }
    

    MainActivity.kt

    package ink.ptlr.fcvt
    
    import androidx.appcompat.app.AppCompatActivity
    import android.os.Bundle
    
    class MainActivity : AppCompatActivity() {
        override fun onCreate(savedInstanceState: Bundle?) {
            // 使用自定义的FragmentFactory,必须在super.onCreate()之前
            supportFragmentManager.fragmentFactory = TestFragment.MyFactory("HELLO FCVT",1024)
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
        }
    }
    

    五、总结

    这个问题是我偷懒,鬼官方太过信任,使用官方模板和不熟悉安卓开发导致的,此外,此处还有一个添加Fragment时会出现空白的问题,今后需要解决。
    PS: 发现并解决这个问题内心十分喜悦,希望能把这种喜悦分享给大家,并对大家有一定帮助。

    相关文章

      网友评论

          本文标题:FragmentContainerView中的问题与解决方法

          本文链接:https://www.haomeiwen.com/subject/remaxrtx.html