问题挖掘
今天改造Navigation的时候使用这段代码, 发生了crash
NavigationUI.setupActionBarWithNavController(this, _navigateKProxy.navController)
从含义得知, 我们需要用到ActionBar却没有
解决方案
主要原因在于全局主题的设置, 在res/values/下的themes.xml查看主题是否为NoActionBar,如果是
- 方案一
更改主题, 改为ActionBar, 这时无问题
- 方案二
如果不想更改主题, 那么可以在Activity的onCreate下加如下代码
setSupportActionBar(findViewById(R.id.xxx))
//或使用viewBinding
setSupportActionBar(vb.xxx)
这里的xxx则为需要的toolbar
在页面上的布局则为:
<?xml version="1.0" encoding="utf-8"?>
<layout 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">
<data />
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".navigatek.NavigateKActivity">
<androidx.appcompat.widget.Toolbar
android:id="@+id/navigatek_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_constraintTop_toTopOf="parent" />
<fragment
android:id="@+id/navigatek_fragment_container"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="0dp"
app:defaultNavHost="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="@id/navigatek_toolbar" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
bingo显示正常!