因此,我试图建立一个应用程序与底部导航栏,将切换之间的片段。我做的编码根据一些文档。
我尝试了互联网上的每一个解决方案,但似乎没有一个适合我。
错误:
Caused by: java.lang.ClassCastException: com.example.jetpacklesson.MainFragment cannot be cast to androidx.navigation.fragment.NavHostFragment
at com.example.jetpacklesson.MainActivity.onCreate(MainActivity.java:30)
下面是XML主活动代码
<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=".MainActivity">
<androidx.fragment.app.FragmentContainerView
android:id="@+id/firstFragmentHolder"
android:layout_width="0dp"
android:layout_height="0dp"
android:name="com.example.jetpacklesson.MainFragment"
app:defaultNavHost = "true"
app:layout_constraintBottom_toTopOf="@+id/bnv_bottomBar"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:navGraph = "@navigation/nav_graph"/>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/bnv_bottomBar"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:menu="@menu/nav_bottom_navigation" />
</androidx.constraintlayout.widget.ConstraintLayout>
和主要活动Java代码:
BottomNavigationView bnv_navigationBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.firstFragmentHolder);
NavController navController = navHostFragment.getNavController();
bnv_navigationBar = findViewById(R.id.bnv_bottomBar);
NavigationUI.setupWithNavController(bnv_navigationBar, navController);
}
1条答案
按热度按时间5kgi1eie1#
您的XML文件显示:
如果您希望它是
NavHostFragment
,则需要将其更改为按照导航入门指南。