问题描述
我正在使用导航视图,并使用导航体系结构组件进行底部导航。它工作正常,但是我无法设置操作栏标题,尽管我已经尝试了所有可用的解决方案,但是没有一个起作用。任何帮助将不胜感激。
MainActivity
class MainActivity : AppCompatActivity {
lateinit var drawerLayout: DrawerLayout
lateinit var navView: NavigationView
lateinit var navController: NavController
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
drawerLayout = findViewById(R.id.drawer_layout)
navView = findViewById(R.id.nav_view)
navController = findNavController(R.id.nav_main_host_fragment)
val toggle = ActionBarDrawerToggle(
this,drawerLayout,toolbar,0)
drawerLayout.addDrawerListener(toggle)
toggle.syncState()
setupDrawerNavigation()
}
private fun setupDrawerNavigation() {
setupActionBarWithNavController(navController)
//NavigationUI.setupActionBarWithNavController(this,navController) // not working
navController.addOnDestinationChangedListener { controller,destination,arguments ->
when (destination.id) {
R.id.navHome -> "My title"
R.id.navProfile -> "Title 2"
R.id.navComments -> "Title 3"
else -> "Default title"
}
}
navView.setupWithNavController(navController)
bottom_main_nav_view.setupWithNavController(navController)
navView.setNavigationItemSelectedListener {
when (it.itemId) {
R.id.navHome -> {
navController.navigate(R.id.navHome)
}
R.id.navProfile -> {
navController.navigate(R.id.navProfile)
}
R.id.navComments-> {
navController.navigate(R.id.navComments)
}
}
drawerLayout.closeDrawer(GravityCompat.START)
true
}
}
}
navigation_main.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/naviagtion"
app:startDestination="@id/navHome">
<fragment
android:id="@+id/navHome"
android:name="com.example.fragments.HomePage"
android:label="@string/home"
tools:layout="@layout/fragment_home" />
<fragment
android:id="@+id/navProfile"
android:name="com.example.fragments.Profile"
android:label="@string/profile"
tools:layout="@layout/fragment_profile" />
<fragment
android:id="@+id/navComments"
android:name="com.example.fragments.navCatchUpTv"
android:label="@string/comments"
tools:layout="@layout/fragment_comments" />
我也尝试过在片段内部进行操作,但没有得到任何结果
(requireActivity() as AppCompatActivity).supportActionBar?.title = "Title"
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)