android 在片段中使用视图绑定时发生膨胀类片段错误

cqoc49vn  于 2023-05-05  发布在  Android
关注(0)|答案(1)|浏览(154)

由于Kotlin1.8强制了视图绑定,所以我在main activity和fragment中实现了它。但我得到错误膨胀类片段
这是主要的活动课。我认为由于视图绑定而导致的主布局膨胀是错误的。我已经初始化了navContoller,在home片段中添加代码之前,它工作正常

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding
    private lateinit var navController: NavController
    private lateinit var appBarConfiguration: AppBarConfiguration
    lateinit var viewModel: MandirViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        val mandirRep = (application as MandirApplication).repository

        val viewModelFactory = MandirViewModelFactory(mandirRep)
        viewModel = ViewModelProvider(this , viewModelFactory).get(MandirViewModel::class.java)

        navController = findNavController(R.id.navContainer)
        appBarConfiguration = AppBarConfiguration(setOf(R.id.homeFragment , R.id.notificationsFragment , R.id.favouriteFragment , R.id.settingsFragment))
        setupActionBarWithNavController(navController , appBarConfiguration)
        binding.bottomNavigationView.setupWithNavController(navController)

{\fnSimHei\bord1\shad1\pos(200,288)}
这里是用于调用API调用的存储库的home片段。我认为这里的错误是夸大了布局。可能是因为视图绑定

class HomeFragment : Fragment() {

    private lateinit var mandirViewModel: MandirViewModel
    private lateinit var mandirAdapter: MandirAdapter
    private lateinit var binding: FragmentHomeBinding

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
         binding = FragmentHomeBinding.inflate(inflater , container , false)

        mandirViewModel = (activity as MainActivity).viewModel
        mandirAdapter = MandirAdapter()

        binding!!.rvMandir.apply {
            adapter = mandirAdapter
            layoutManager = LinearLayoutManager(context)
        }

        mandirViewModel.mAndirs.observe( viewLifecycleOwner , Observer {
            it.let { response->
                mandirAdapter.differ.submitList(response.data)

            }

        })

        return view
    }

}

这是应用程序类。我已经用它来初始化仓库使用示例的改造类

class MandirApplication : Application() {

    lateinit var repository: MandirRepository

    override fun onCreate() {
        super.onCreate()

        initialize()
    }

    private fun initialize() {

        val mandirService = RetrofitHelper.getInstance().create(MandirAPI::class.java)
        repository = MandirRepository( mandirService , applicationContext)
    }
}

下面是主活动的XML文件。我已经使用了框架布局,因为我在这里读到片段视图需要框架布局来跨片段移动

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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=".ui.MainActivity">

        <fragment
            android:id="@+id/navContainer"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            app:defaultNavHost="true"
            app:layout_constraintBottom_toTopOf="@+id/bottomNavigationView"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:navGraph="@navigation/navgraph" />

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottomNavigationView"
        android:layout_width="match_parent"
        android:layout_height="70dp"
        android:layout_gravity="bottom"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.997"
        app:menu="@menu/menu" />

</FrameLayout>

下面是home Fragment的XML文件。在主片段中扩展此布局是一个错误

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.HomeFragment">

    <androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/rvMandir"/>

</FrameLayout>

这是错误日志。不知道是不是显示viewModel未初始化。它也显示问题在充气布局请帮助
2023-05-03 15:38:17.103 1931-1931 AndroidRuntime com.example.mandirapp E致命异常:主要的

Process: com.example.mandirapp, PID: 1931
                                                                                                    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mandirapp/com.example.mandirapp.ui.MainActivity}: android.view.InflateException: Binary XML file line #19 in com.example.mandirapp:layout/activity_main: Binary XML file line #19 in com.example.mandirapp:layout/activity_main: Error inflating class fragment
                                                                                                        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3635)
                                                                                                        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3792)
                                                                                                        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103)
                                                                                                        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
                                                                                                        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
                                                                                                        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2210)
                                                                                                        at android.os.Handler.dispatchMessage(Handler.java:106)
                                                                                                        at android.os.Looper.loopOnce(Looper.java:201)
                                                                                                        at android.os.Looper.loop(Looper.java:288)
                                                                                                        at android.app.ActivityThread.main(ActivityThread.java:7839)
                                                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                                                        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
                                                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
                                                                                                    Caused by: android.view.InflateException: Binary XML file line #19 in com.example.mandirapp:layout/activity_main: Binary XML file line #19 in com.example.mandirapp:layout/activity_main: Error inflating class fragment
                                                                                                    Caused by: android.view.InflateException: Binary XML file line #19 in com.example.mandirapp:layout/activity_main: Error inflating class fragment
                                                                                                    Caused by: kotlin.UninitializedPropertyAccessException: lateinit property viewModel has not been initialized
                                                                                                        at com.example.mandirapp.ui.MainActivity.getViewModel(MainActivity.kt:25)
                                                                                                        at com.example.mandirapp.ui.HomeFragment.onCreateView(HomeFragment.kt:34)
                                                                                                        at androidx.fragment.app.Fragment.performCreateView(Fragment.java:3104)
                                                                                                        at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:524)
                                                                                                        at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:261)
                                                                                                        at androidx.fragment.app.FragmentStore.moveToExpectedState(FragmentStore.java:113)
                                                                                                        at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1433)
                                                                                                        at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2977)
                                                                                                        at androidx.fragment.app.FragmentManager.dispatchViewCreated(FragmentManager.java:2888)
                                                                                                        at androidx.fragment.app.Fragment.performViewCreated(Fragment.java:3129)
                                                                                                        at androidx.fragment.app.FragmentStateManager.ensureInflatedView(FragmentStateManager.java:394)
                                                                                                        at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:260)
                                                                                                        at androidx.fragment.app.FragmentLayoutInflaterFactory.onCreateView(FragmentLayoutInflaterFactory.java:142)
                                                                                                        at androidx.fragment.app.FragmentController.onCreateView(FragmentController.java:136)
                                                                                                        at androidx.fragment.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:248)
                                                                                                        at androidx.fragment.app.FragmentActivity.onCreateView(FragmentActivity.java:227)
                                                                                                        at android.view.LayoutInflater.tryCreateView(LayoutInflater.java:1073)
                                                                                                        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:1001)
                                                                                                        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:965)
                                                                                                        at android.view.LayoutInflater.rInflate(LayoutInflater.java:1127)
                                                                                                        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1088)
                                                                                                        at android.view.LayoutInflater.inflate(LayoutInflater.java:686)
                                                                                                        at android.view.LayoutInflater.inflate(LayoutInflater.java:538)
                                                                                                        at com.example.mandirapp.databinding.ActivityMainBinding.inflate(ActivityMainBinding.java:45)
                                                                                                        at com.example.mandirapp.databinding.ActivityMainBinding.inflate(ActivityMainBinding.java:39)
                                                                                                        at com.example.mandirapp.ui.MainActivity.onCreate(MainActivity.kt:30)
                                                                                                        at android.app.Activity.performCreate(Activity.java:8051)
2023-05-03 15:38:17.104  1931-1931  AndroidRuntime          com.example.mandirapp                E      at android.app.Activity.performCreate(Activity.java:8031)
                                                                                                        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1329)
                                                                                                        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3608)
                                                                                                        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3792)
                                                                                                        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103)
                                                                                                        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
                                                                                                        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
                                                                                                        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2210)
                                                                                                        at android.os.Handler.dispatchMessage(Handler.java:106)
                                                                                                        at android.os.Looper.loopOnce(Looper.java:201)
                                                                                                        at android.os.Looper.loop(Looper.java:288)
                                                                                                        at android.app.ActivityThread.main(ActivityThread.java:7839)
                                                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                                                        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
                                                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
2ul0zpep

2ul0zpep1#

这是因为你必须在onCreateView()方法中返回膨胀的视图。在你的例子中,它是binding.root。就像这样:

class HomeFragment : Fragment() {

  private lateinit var mandirViewModel: MandirViewModel
  private lateinit var mandirAdapter: MandirAdapter
  private lateinit var binding: FragmentHomeBinding

  override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
  ): View? {
    // Inflate the layout for this fragment
     binding = FragmentHomeBinding.inflate(inflater , container , false)

    mandirViewModel = (activity as MainActivity).viewModel
    mandirAdapter = MandirAdapter()

    binding!!.rvMandir.apply {
        adapter = mandirAdapter
        layoutManager = LinearLayoutManager(context)
    }

    mandirViewModel.mAndirs.observe( viewLifecycleOwner , Observer {
        it.let { response->
            mandirAdapter.differ.submitList(response.data)

        }

    })

    return binding.root
  }

}

相关问题