Fragment 中的 findNavController() 给出 "does not have a NavController set" 错误
findNavController() in Fragment gives "does not have a NavController set" error
我是 Android 开发的新手,几天来我一直被这个错误所困..
我有一个带有 FragmentContainerView 和 BottomNavigationView 的 activity。 BottomNavigationView 有 2 个片段可供切换:ScanFragment 和 ProfileFragment。
当我切换到 ProfileFragment 并使用以下代码按下按钮 (payMethodButton) 时:
val payMethodButton = view.findViewById<TableRow>(R.id.trMyPayMethod)
payMethodButton.setOnClickListener {
findNavController().navigate(
R.id.action_profileFragment_to_bankFragment
)
}
应用程序将崩溃并显示此错误消息:View androidx.constraintlayout.widget.ConstraintLayout{2aaced1 V.E...... ........ 0,0-1080,1668} does not have a NavController set
我做错了什么?为什么没有 NavController?
DashboardActivity.kt
package com.app.app.activities.dashboard
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.app.app.R
import com.app.app.activities.BaseActivity
import com.app.app.fragments.ProfileFragment
import com.app.app.fragments.ScanFragment
class DashboardActivity : BaseActivity() {
private val scanFragment: Fragment = ScanFragment()
private val profileFragment: Fragment = ProfileFragment()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_dashboard)
val navigation = findViewById<View>(R.id.bottomNavigationView) as BottomNavigationView
navigation.setOnItemSelectedListener { item ->
when (item.itemId) {
R.id.navigation_scan -> replaceFragment(scanFragment)
R.id.navigation_profile -> replaceFragment(profileFragment)
}
true
}
}
private fun replaceFragment(fragment: Fragment) {
val transaction = supportFragmentManager.beginTransaction()
transaction.replace(R.id.dashboardNavHostFragment, fragment)
transaction.commit()
}
}
activity_dashboard.xml
<?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"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.fragment.app.FragmentContainerView
android:id="@+id/dashboardNavHostFragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="0dp"
app:defaultNavHost="true"
app:layout_constraintBottom_toTopOf="@+id/bottomNavigationView"
app:layout_constraintTop_toTopOf="parent"
app:navGraph="@navigation/dashboard_nav" />
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/bottomNavigationView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/bottom_menu_bar"
app:itemIconTint="@drawable/bottom_nav_selector"
app:itemTextAppearanceActive="@style/BottomNavigationView.Active"
app:itemTextAppearanceInactive="@style/BottomNavigationView"
app:itemTextColor="@drawable/bottom_nav_selector"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:menu="@menu/bottom_dash_menu" />
</androidx.constraintlayout.widget.ConstraintLayout>
ProfileFragment.kt
package com.app.app.fragments
import android.app.AlertDialog
import android.content.Intent
import android.os.Bundle
import android.view.*
import android.widget.TableRow
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.NavHost
import androidx.navigation.Navigation
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.fragment.findNavController
import com.app.app.BuildConfig
import com.app.app.R
import com.app.app.activities.account.login.LoginActivity
class ProfileFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_profile, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
(activity as AppCompatActivity).supportActionBar?.title = "Profile"
val payMethodButton = view.findViewById<Button>(R.id.btPayMethod)
payMethodButton.setOnClickListener {
findNavController().navigate(
R.id.action_profileFragment_to_bankFragment
)
}
}
}
dashboard_nav.xml
<?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/dashboard_nav"
app:startDestination="@id/scanFragment">
<fragment
android:id="@+id/scanFragment"
android:name="com.app.app.fragments.ScanFragment"
android:label="fragment_scan"
tools:layout="@layout/fragment_scan" />
<fragment
android:id="@+id/profileFragment"
android:name="com.app.app.fragments.ProfileFragment"
android:label="fragment_profile"
tools:layout="@layout/fragment_profile">
<action
android:id="@+id/action_profileFragment_to_bankFragment"
app:destination="@id/bankFragment" />
</fragment>
<fragment
android:id="@+id/bankFragment"
android:name="com.app.app.fragments.BankFragment"
android:label="BankFragment"
tools:layout="@layout/fragment_bank" />
</navigation>
崩溃:
2022-02-04 18:09:44.524 23247-23247/com.app.app E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.app.app, PID: 23247
java.lang.IllegalStateException: View androidx.constraintlayout.widget.ConstraintLayout{2aaced1 V.E...... ........ 0,0-1080,1668} does not have a NavController set
at androidx.navigation.Navigation.findNavController(Navigation.java:84)
at androidx.navigation.fragment.NavHostFragment.findNavController(NavHostFragment.java:120)
at androidx.navigation.fragment.FragmentKt.findNavController(Fragment.kt:29)
at com.app.app.fragments.ProfileFragment.onViewCreated$lambda-0(ProfileFragment.kt:45)
at com.app.app.fragments.ProfileFragment.$r8$lambda[=16=]UCyAyd5HwAmhAbNeILyUNaedgA(Unknown Source:0)
at com.app.app.fragments.ProfileFragment$$ExternalSyntheticLambda2.onClick(Unknown Source:2)
at android.view.View.performClick(View.java:7862)
at android.view.View.performClickInternal(View.java:7831)
at android.view.View.access00(View.java:879)
at android.view.View$PerformClick.run(View.java:29359)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:8167)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:496)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1100)
我从 Github 下载了一个 example,它帮助我解决了这个问题。
根据示例,这段代码对我有用:
class DashboardActivity : BaseActivity() {
private lateinit var navController: NavController
private lateinit var appBarConfiguration: AppBarConfiguration
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_dashboard)
val navHostFragment = supportFragmentManager.findFragmentById(
R.id.dashboardNavHostFragment
) as NavHostFragment
navController = navHostFragment.navController
// Setup the bottom navigation view with navController
val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottomNavigationView)
bottomNavigationView.setupWithNavController(navController)
// Setup the ActionBar with navController and 2 top level destinations
appBarConfiguration = AppBarConfiguration(
setOf(R.id.scanFragment, R.id.profileFragment)
)
setupActionBarWithNavController(navController, appBarConfiguration)
}
override fun onSupportNavigateUp(): Boolean {
return navController.navigateUp(appBarConfiguration)
}
}
我是 Android 开发的新手,几天来我一直被这个错误所困..
我有一个带有 FragmentContainerView 和 BottomNavigationView 的 activity。 BottomNavigationView 有 2 个片段可供切换:ScanFragment 和 ProfileFragment。
当我切换到 ProfileFragment 并使用以下代码按下按钮 (payMethodButton) 时:
val payMethodButton = view.findViewById<TableRow>(R.id.trMyPayMethod)
payMethodButton.setOnClickListener {
findNavController().navigate(
R.id.action_profileFragment_to_bankFragment
)
}
应用程序将崩溃并显示此错误消息:View androidx.constraintlayout.widget.ConstraintLayout{2aaced1 V.E...... ........ 0,0-1080,1668} does not have a NavController set
我做错了什么?为什么没有 NavController?
DashboardActivity.kt
package com.app.app.activities.dashboard
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.app.app.R
import com.app.app.activities.BaseActivity
import com.app.app.fragments.ProfileFragment
import com.app.app.fragments.ScanFragment
class DashboardActivity : BaseActivity() {
private val scanFragment: Fragment = ScanFragment()
private val profileFragment: Fragment = ProfileFragment()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_dashboard)
val navigation = findViewById<View>(R.id.bottomNavigationView) as BottomNavigationView
navigation.setOnItemSelectedListener { item ->
when (item.itemId) {
R.id.navigation_scan -> replaceFragment(scanFragment)
R.id.navigation_profile -> replaceFragment(profileFragment)
}
true
}
}
private fun replaceFragment(fragment: Fragment) {
val transaction = supportFragmentManager.beginTransaction()
transaction.replace(R.id.dashboardNavHostFragment, fragment)
transaction.commit()
}
}
activity_dashboard.xml
<?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"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.fragment.app.FragmentContainerView
android:id="@+id/dashboardNavHostFragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="0dp"
app:defaultNavHost="true"
app:layout_constraintBottom_toTopOf="@+id/bottomNavigationView"
app:layout_constraintTop_toTopOf="parent"
app:navGraph="@navigation/dashboard_nav" />
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/bottomNavigationView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/bottom_menu_bar"
app:itemIconTint="@drawable/bottom_nav_selector"
app:itemTextAppearanceActive="@style/BottomNavigationView.Active"
app:itemTextAppearanceInactive="@style/BottomNavigationView"
app:itemTextColor="@drawable/bottom_nav_selector"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:menu="@menu/bottom_dash_menu" />
</androidx.constraintlayout.widget.ConstraintLayout>
ProfileFragment.kt
package com.app.app.fragments
import android.app.AlertDialog
import android.content.Intent
import android.os.Bundle
import android.view.*
import android.widget.TableRow
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.NavHost
import androidx.navigation.Navigation
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.fragment.findNavController
import com.app.app.BuildConfig
import com.app.app.R
import com.app.app.activities.account.login.LoginActivity
class ProfileFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_profile, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
(activity as AppCompatActivity).supportActionBar?.title = "Profile"
val payMethodButton = view.findViewById<Button>(R.id.btPayMethod)
payMethodButton.setOnClickListener {
findNavController().navigate(
R.id.action_profileFragment_to_bankFragment
)
}
}
}
dashboard_nav.xml
<?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/dashboard_nav"
app:startDestination="@id/scanFragment">
<fragment
android:id="@+id/scanFragment"
android:name="com.app.app.fragments.ScanFragment"
android:label="fragment_scan"
tools:layout="@layout/fragment_scan" />
<fragment
android:id="@+id/profileFragment"
android:name="com.app.app.fragments.ProfileFragment"
android:label="fragment_profile"
tools:layout="@layout/fragment_profile">
<action
android:id="@+id/action_profileFragment_to_bankFragment"
app:destination="@id/bankFragment" />
</fragment>
<fragment
android:id="@+id/bankFragment"
android:name="com.app.app.fragments.BankFragment"
android:label="BankFragment"
tools:layout="@layout/fragment_bank" />
</navigation>
崩溃:
2022-02-04 18:09:44.524 23247-23247/com.app.app E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.app.app, PID: 23247
java.lang.IllegalStateException: View androidx.constraintlayout.widget.ConstraintLayout{2aaced1 V.E...... ........ 0,0-1080,1668} does not have a NavController set
at androidx.navigation.Navigation.findNavController(Navigation.java:84)
at androidx.navigation.fragment.NavHostFragment.findNavController(NavHostFragment.java:120)
at androidx.navigation.fragment.FragmentKt.findNavController(Fragment.kt:29)
at com.app.app.fragments.ProfileFragment.onViewCreated$lambda-0(ProfileFragment.kt:45)
at com.app.app.fragments.ProfileFragment.$r8$lambda[=16=]UCyAyd5HwAmhAbNeILyUNaedgA(Unknown Source:0)
at com.app.app.fragments.ProfileFragment$$ExternalSyntheticLambda2.onClick(Unknown Source:2)
at android.view.View.performClick(View.java:7862)
at android.view.View.performClickInternal(View.java:7831)
at android.view.View.access00(View.java:879)
at android.view.View$PerformClick.run(View.java:29359)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:8167)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:496)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1100)
我从 Github 下载了一个 example,它帮助我解决了这个问题。
根据示例,这段代码对我有用:
class DashboardActivity : BaseActivity() {
private lateinit var navController: NavController
private lateinit var appBarConfiguration: AppBarConfiguration
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_dashboard)
val navHostFragment = supportFragmentManager.findFragmentById(
R.id.dashboardNavHostFragment
) as NavHostFragment
navController = navHostFragment.navController
// Setup the bottom navigation view with navController
val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottomNavigationView)
bottomNavigationView.setupWithNavController(navController)
// Setup the ActionBar with navController and 2 top level destinations
appBarConfiguration = AppBarConfiguration(
setOf(R.id.scanFragment, R.id.profileFragment)
)
setupActionBarWithNavController(navController, appBarConfiguration)
}
override fun onSupportNavigateUp(): Boolean {
return navController.navigateUp(appBarConfiguration)
}
}