我不知道是什么导致错误。这是我第一次使用导航。请帮我。首先,从底部导航中输入活动。然后,错误代码是“致命异常:主要:
Process: com.example.manager1, PID: 9184
java.lang.IllegalStateException: ~~
View does not have a NavController set "
它是在访问新活动(家庭)时发生的。
这是我的导航图:
<?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_household"
app:startDestination="@+id/HouseholdFragment">
<!-- HouseholdFragment -->
<fragment android:id="@+id/HouseholdFragment"
android:name="com.example.manager1.navigation.
HouseholdFragment"
android:label="fragment_household"
tools:layout="@layout/fragment_household" >
<action
android:id="@+id/action_HouseholdFragment_to_
ViewBalanceFragment"
app:destination="@id/ViewBalanceFragment" />
<action
android:id="@+id/action_HouseholdFragment_to_
ViewAnalysisFragment"
app:destination="@id/ViewAnalysisFragment" />
</fragment>
<!-- ViewBalanceFragment -->
<fragment android:id="@+id/ViewBalanceFragment" `
android:name="com.example.manager1.navigation.
ViewBalanceFragment"
android:label="fragment_view_balance"
tools:layout="@layout/fragment_view_balance" >
</fragment>
<!-- ViewAnalysisFragment -->
<fragment android:id="@+id/ViewAnalysisFragment"
android:name="com.example.manager1.navigation.
ViewAnalysisFragment"
android:label="fragment_view_analysis"
</fragment>
</navigation>
这是我的片段(kotlin)
class HouseholdFragment : Fragment(),View.OnClickListener
{
lateinit var navController: NavController
......
override fun onViewCreated(view: View, savedInstanceState:
Bundle?) {
super.onViewCreated(view, savedInstanceState)
navController = Navigation.findNavController(view)
view.findViewById<Button>
(R.id.view_balance_btn).setOnClickListener(this)
view.findViewById<Button>
(R.id.view_analysis_btn).setOnClickListener(this)
}
这是我的主要活动
open class MainActivity : AppCompatActivity()
,BottomNavigationView.OnNavigationItemSelectedListener {
override fun onNavigationItemSelected(p0: MenuItem):
Boolean {
when (p0.itemId) {
...
R.id.action_houeshold -> {
var householdFragment = HouseholdFragment()
supportFragmentManager.beginTransaction()
.replace(R.id.main_content, householdFragment).commit()
startActivity(Intent(this,
HouseholdActivity::class.java))
finish()
return true
...
}
这是我的manifest.xml
<activity
android:name=".LoadingActivity"
android:theme="@style/LoadingTheme" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"
/>
</intent-filter>
</activity>
<activity android:name=".MainActivity">
</activity>
<activity android:name=".HouseholdActivity">
</activity>
因此,HouseholdActivity刚刚设置了ContentContentview(R.layout.actvitiy_household)