首页 > 解决方案 > 在 Koltlin 中膨胀类片段时出错

问题描述

我调试了一整天都没有结果

我得到错误

    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.b_hero/com.example.b_hero.MainActivity}: android.view.InflateException: Binary XML file line #9 in com.example.b_hero:layout/activity_main: Binary XML file line #9 in com.example.b_hero:layout/activity_main: Error inflating class fragment

我读了错误膨胀类片段,但它对我不起作用

activity_main.xml


<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical">
        <fragment
            android:id="@+id/myNavHostFrgment"
            android:name="com.example.b_hero.SignIn.SignInFragment"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            app:navGraph="@navigation/nav_graph"
            app:defaultNavHost= "true"
            />

    </LinearLayout>

</layout> 

第 9 行是 <fragment 标签

SignInFragment 类

package com.example.b_hero.SignIn
import android.os.Bundle
import android.view.*
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.navigation.Navigation
import androidx.navigation.findNavController
import androidx.navigation.ui.NavigationUI
import com.example.b_hero.R
import com.example.b_hero.databinding.FragmentSignInBinding

class SignInFragment : Fragment() {
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val binding: FragmentSignInBinding =
            DataBindingUtil.inflate(inflater, R.layout.fragment_sign_in, container, false)

        binding.apply {  
  signInButton.setOnClickListener(Navigation.createNavigateOnClickListener(R.id.action_signInFragment_to_signUp))
        }
        return binding.root
    }
}

标签: androidkotlin

解决方案


        <fragment
            android:id="@+id/myNavHostFrgment"
            android:name="com.example.b_hero.SignIn.SignInFragment"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            app:navGraph="@navigation/nav_graph"
            app:defaultNavHost= "true"
            />

片段更改为片段


推荐阅读