2022年9月26日 星期一

【Android 問題解決】cannot be cast to androidx.navigation.fragment.NavHostFragment

2022-09-26 23:55:20.218 4898-4898/com.example.elderlyshoppingwithfab E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.elderlyshoppingwithfab, PID: 4898 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.elderlyshoppingwithfab/com.example.elderlyshoppingwithfab.ScannerResultActivity}: java.lang.ClassCastException: com.example.elderlyshoppingwithfab.ScannerSimpleResultFragment cannot be cast to androidx.navigation.fragment.NavHostFragment at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:4035)  (略)


問題解決:

<androidx.constraintlayout.widget.ConstraintLayout 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=".ScannerResultActivity">

<androidx.fragment.app.FragmentContainerView
android:id="@+id/nav_host_fragment"
android:name="com.example.elderlyshoppingwithfab.ScannerSimpleResultFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"

app:defaultNavHost="true"
app:navGraph="@navigation/nav_graph"/>

</androidx.constraintlayout.widget.ConstraintLayout>

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".ScannerResultActivity">

<androidx.fragment.app.FragmentContainerView
android:id="@+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"

app:defaultNavHost="true"
app:navGraph="@navigation/nav_graph"/>

</androidx.constraintlayout.widget.ConstraintLayout>

感謝
android - NullPointerException Error while trying to create navHostFragment - Stack Overflow

0 comments:

張貼留言