我有一個由 Google 推薦的一個活動和幾個片段組成的應用程式。
- MainActivity
- LobbyFragment
- GameFragment
- ...
我也想用導航圖

我在Activity里放了一個選單到處都有,然后我想切換頁面的內容。
為此,如片段教程中所示,我activitymain.xml稍后FragmentContainerView在片段之間切換內容。
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/transparent"
android:theme="@style/Theme.application.AppBarOverlay">
</com.google.android.material.appbar.AppBarLayout>
<androidx.fragment.app.FragmentContainerView
android:id="@ id/fragment_container_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.my.application.LobbyFragment" /> <!--Here is failure-->
</androidx.coordinatorlayout.widget.CoordinatorLayout>
但是,此時,當我編譯時,我有:
Unable to start activity ComponentInfo{com.my.application/com.my.application.MainActivity}: android.view.InflateException: Binary XML file line #21: Binary XML file line #21: Error inflating class androidx.fragment.app.FragmentContainerView
以及將 Activity 放在導航地圖中的什么位置?
uj5u.com熱心網友回復:
您參考的檔案鏈接通過直接訪問使用了傳統的片段事務supportFragmentManager;但從您的帖子中可以看出,您使用的是導航架構組件。
在導航組件中,您不應該在android:name屬性中使用特定的片段類,而是navController使用NavHostFragment
要解決這個問題,請更換
android:name="com.my.application.LobbyFragment"
和
android:name="androidx.navigation.fragment.NavHostFragment"
此外,您需要在app:navGraph屬性中參考導航圖的名稱;假設它被命名為nav_graph:
app:navGraph="@navigation/nav_graph"
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/342716.html
標籤:安卓 android-fragments 安卓活动 android-架构-组件
