如何修复由目的地引起的膨胀错误不是此 NavGraph 的直接子级

Posted

技术标签:

【中文标题】如何修复由目的地引起的膨胀错误不是此 NavGraph 的直接子级【英文标题】:How to fix inflating error caused by destination is not a direct child of this NavGraph 【发布时间】:2019-10-18 17:51:05 【问题描述】:

我有一个简单的应用程序,其中包含一个主要活动、一个片段 frag_home 和一个名为 ItemFragment 的列表片段。 在frag_home 我有一个日历视图。如果用户选择一个日期,frag_homeDirections.actionFragHomeToItemFragment(mytimeinmillis) 操作会打开显示所选日期事件的列表片段。该操作使用参数timeinmillis,它以毫秒为单位保存选定的日期。

一切正常。但是,如果我想创建一个两个面板视图并将 listfragment 实现到主片段的布局中(只需使用 xml 编辑器,选择 activity_main.xml,将片段组件拖到 activity_main 并选择 listItem)我会收到以下错误,如果我尝试运行我的应用程序:

E/androidRuntime: FATAL EXCEPTION: main
    Process: com.example.myapplication, PID: 8401
    java.lang.RuntimeException: Unable to start activity ComponentInfocom.example.myapplication/com.example.myapplication.MainActivity: android.view.InflateException: Binary XML file line #29: Binary XML file line #29: Error inflating class fragment
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2756)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2817)
        at android.app.ActivityThread.-wrap12(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1556)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:163)
        at android.app.ActivityThread.main(ActivityThread.java:6388)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:930)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:820)
     Caused by: android.view.InflateException: Binary XML file line #29: Binary XML file line #29: Error inflating class fragment
     Caused by: android.view.InflateException: Binary XML file line #29: Error inflating class fragment
     Caused by: java.lang.IllegalArgumentException: navigation destination com.example.myapplication:id/destination_home is not a direct child of this NavGraph

这是我实现片段 ItemFragment 的主要活动

?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout
        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/drawer_layout"
        android:layout_
        android:layout_
        tools:context=".MainActivity">
<LinearLayout
        android:layout_
        android:layout_
        android:orientation="vertical"
        tools:context=".MainActivity" >


    <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_
            android:layout_
            android:background="?attr/colorPrimary"
            android:theme="?attr/actionBarTheme"

    />


    <com.google.android.material.bottomnavigation.BottomNavigationView
            android:id="@+id/bottom_nav"
            android:layout_
            android:layout_
            app:menu="@menu/menu_navigation"/>
    <fragment
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_
            android:layout_ app:navGraph="@navigation/nav_graph" app:defaultNavHost="true"
            android:id="@+id/nav_host_fragment"/>
    <fragment
            android:layout_
            android:layout_ android:name="com.example.myapplication.ItemFragment"
            android:id="@+id/fragment"/>


</LinearLayout>
<com.google.android.material.navigation.NavigationView
android:id="@+id/nav_view"
android:layout_
android:layout_
android:layout_gravity="start"
app:menu="@menu/menu_navigation"/>
        </androidx.drawerlayout.widget.DrawerLayout >

这是我的导航图

?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/frag_home">

    <fragment android:id="@+id/itemFragment" android:name="com.example.myapplication.ItemFragment"
              android:label="ItemFragment" tools:layout="@layout/fragment_item">
        <argument android:name="timeinmillis" app:argType="long" />
    </fragment>
    <fragment android:id="@+id/frag_home" android:name="com.example.myapplication.frag_home"
              android:label="fragment_main" tools:layout="@layout/frag_home">
        <action android:id="@+id/action_frag_home_to_itemFragment" app:destination="@id/itemFragment"/>
        <action android:id="@+id/action_frag_home_to_create_Event" app:destination="@id/create_Event"/>
    </fragment>
    <fragment android:id="@+id/create_Event" android:name="com.example.myapplication.Create_Event"
              android:label="fragment_create__event" tools:layout="@layout/fragment_create__event"/>
</navigation> 

我的主要活动

class MainActivity : AppCompatActivity() 
    private lateinit var linearLayoutManager: LinearLayoutManager
    override fun onCreate(savedInstanceState: Bundle?) 
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
       //linearLayoutManager = LinearLayoutManager(this)
        //list2_recycler_view.layoutManager = linearLayoutManager
        setSupportActionBar(toolbar)
        val navController = Navigation.findNavController(this,R.id.nav_host_fragment)


        setupBottomNavMenu(navController)

        setupActionBar(navController)
    setupSideNavigationMenu(navController)
    

我的家庭片段:

class frag_home : Fragment() 

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? 
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.frag_home, container, false)
    

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) 
        super.onViewCreated(view, savedInstanceState)

        btnCreateEvent.setOnClickListener
           //val date = "heute"
            val action = frag_homeDirections.actionFragHomeToCreateEvent()
            val openHandler = My_Clients_OpenHandler()
            val selected_date = Calendar.getInstance().timeInMillis
           // action.setStrDatum("Bussi!")
          Navigation.findNavController(it).navigate(action)


        
        btnListe.setOnClickListener
            //val date = "heute"
            val caltmp = Calendar.getInstance()
            val mytimeinmillis = caltmp.timeInMillis
            val action = frag_homeDirections.actionFragHomeToItemFragment(mytimeinmillis)
            val openHandler = My_Clients_OpenHandler()
            // action.setStrDatum("Bussi!")

          Navigation.findNavController(it).navigate(action)


        
        calendarView?.setOnDateChangeListener  view, year, month, dayOfMonth ->
            // Note that months are indexed from 0. So, 0 means January, 1 means february, 2 means march etc.

            val selected_date = "Selected date is " + dayOfMonth + "/" + (month + 1) + "/" + year
            val caltmp = Calendar.getInstance()
            //val newdatetime = DateTime(year,month, dayOfMonth)
            caltmp.set(year,month,dayOfMonth)
            val mytimeinmillis = caltmp.timeInMillis
            val sdf = SimpleDateFormat("dd.MM.yyyy HH:mm")
            val strSelectedDate = sdf.format(caltmp.getTime())
            val action = frag_homeDirections.actionFragHomeToItemFragment(mytimeinmillis)


              view.findNavController().navigate(action)
          //  actionCreateEvent.setStrDatum(msg)
          //  Navigation.findNavController(view).navigate(actionCreateEvent)
        


    


如果你需要 itemfragment 的重要部分

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

        arguments?.let 
            columnCount = it.getInt(ARG_COLUMN_COUNT)
        
    

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? 
        val view = inflater.inflate(
            R.layout.fragment_recyclerview,
            container,
            false
        )
        //val timeinmillis = arguments?.let  ItemFragmentArgs.fromBundle(it).timeinmillis 
        // val selecteddate = ItemFragmentArgs.fromBundle(arguments)
        //getActivity()?.setTitle(selecteddate);
        // Set the adapter
      var linearLayoutManager: LinearLayoutManager


        openCalendar = OpenCalendarHandler(activity)
        val caltemp = Calendar.getInstance();
        val longTimeinMillis = arguments?.let  ItemFragmentArgs.fromBundle(it).timeinmillis 

        caltemp.timeInMillis = longTimeinMillis!!


        val heute = caltemp.timeInMillis

        val intCalendarId = openCalendar.getCalendarIdbyCalendarName(view.context, "Klienten_Rolandcloud")
        val strCalendarId = intCalendarId!!.toString()
        // alle events vom aktuell im Kalendar_Monat ausgew�hlten Tag
        val selection = ("((" + CalendarContract.Events.DTSTART + " >= ?) AND ("
                + CalendarContract.Events.DTEND + " <= ?) AND ("
                + CalendarContract.Events.DELETED + " = ?) AND ("
                + CalendarContract.Events.CALENDAR_ID + " = ?))")

        val t = Time()
        t.set(caltemp.getTimeInMillis())

        // Ende des Tages indem ich die Uhrzeit auf 23:59 und 59 Sekunden
        // stelle..
        t.set(59, 59, 23, t.monthDay, t.month, t.year)
        val dtEnd = java.lang.Long.toString(t.toMillis(false))
        val strEnde = openCalendar.getStringTimeinMillis(
            t.toMillis(false),
            "yyyy-MM-dd HH:mm"
        )

        // Start des Tages bei 00:00
        t.set(0, 0, 0, t.monthDay, t.month, t.year)
        val strStart = openCalendar.getStringTimeinMillis(
            t.toMillis(false),
            "yyyy-MM-dd HH:mm"
        )
        val dtStart = java.lang.Long.toString(t.toMillis(false))


        val selectionArgs = arrayOf(dtStart, dtEnd, "0", intCalendarId.toString())

        //my_recyclerview  // Add this
        val activity = activity as Context
        val my_recycler_view = view.findViewById<RecyclerView>(R.id.my_recycler_view)
        val meinCursor = openCalendar.getEvents(view.context,selection,selectionArgs,null)
       //linearLayoutManager = LinearLayoutManager(activity)

        view.my_recycler_view.layoutManager = LinearLayoutManager(activity)
        // set the custom adapter to the RecyclerView
        view.my_recycler_view.adapter = MyCalendarAdapter_kotlin(view.context,meinCursor)



        return view
    

    override fun onActivityCreated(savedInstanceState: Bundle?) 
        super.onActivityCreated(savedInstanceState)
        LoaderManager.getInstance(this).initLoader(EVENTLOADER_ID, null, this)
    
    // populate the views now that the layout has been inflated
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) 
        super.onViewCreated(view, savedInstanceState)
        // RecyclerView node initialized here
        my_recycler_view.apply 
            // set a LinearLayoutManager to handle Android
            // RecyclerView behavior
            val caltmp = Calendar.getInstance()

        
    

/*

如果我想将 listfragment 实现到 activity_main 片段中,我该如何解决这个错误。我的目标:查看带有日历视图的片段 frag_home 以及带有当天事件的列表片段。全部通过使用导航组件和操作。

或者说不能用导航组件导航到一个fragment,在其他布局中实现? 谢谢!!

【问题讨论】:

你在哪里使用destination_home 碎片——家应该是目的地——家。它是起始的家庭片段。我删除了第一个导航图,因为所有安全的 args 类突然消失了。在那个导航图中,我将标签命名为 frag-home destination-home(在导航编辑器中) 您是否尝试过从 app:startDestination="@+id/ 中删除“+”? 【参考方案1】:

确保您指定了起始片段。由于某种原因,我没有起始片段,一旦修复,就纠正了“不是直接子错误”。

确保在片段上指定了 Start

【讨论】:

以上是关于如何修复由目的地引起的膨胀错误不是此 NavGraph 的直接子级的主要内容,如果未能解决你的问题,请参考以下文章

如何修复由 Pycharm 中的 Tensorflow 引起的 cudart64_110.dll 错误?

如何修复由 Caused by: java.lang.NumberFormatException: For input string: "pets" 引起的 Asynctask 错

如何修复“错误膨胀类 android.support.design.widget.NavigationView”

Android 活动未在某些设备上启动(错误膨胀类)

如何修复由 lambda 事件处理程序引起的 GC 周期?

如何使用 yfinance 下载数据修复此错误