close

在使用 Navigation 的時候遇上的問題

 

This navigation graph is not referenced to any layout files(expected to find it in at least one layout file with a NavHostFragment with app:navGraph="@navigation/@navigation" attribute

 

從字面上的意思是我沒有設定這個 navigation.xml 的依賴 layout

但我明明就設定在 main_activity.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:id="@+id/container"
    android:name="androidx.navigation.fragment.NavHostFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:defaultNavHost="true"
    app:navGraph="@navigation/main_nav"
    tools:context=".MainActivity" />

1、android:name="androidx.navigation.fragment.NavHostFragment"

2、app:defaultNavHost="true"

3、app:navGraph="@navigation/main_nav"

皆有設定,但錯誤依然沒有消失

 

後來改了一下 main_activity 的寫法

<?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=".MainActivity">

    <fragment
        android:id="@+id/container"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:navGraph="@navigation/main_nav" />
</FrameLayout>

主要是 <fragment> 這個元素

第一種寫法,我們是把 NavHostFragment 宣告在 <FrameLayout> 裡面

所以並不算生效

改宣告在 <fragment> 之中就正常了

 

由於 Android Studio init project 時預設 generate 的是第一種寫法

所以也沒想太多就下意識的加在 fields 之間

希望有幫助到陷入同樣誤區的大家

 

 


arrow
arrow

    顏澤偉 發表在 痞客邦 留言(0) 人氣()