【发布时间】:2019-11-29 01:41:10
【问题描述】:
这里是要下载的项目:https://www.dropbox.com/s/lq3p2pnwjacik7s/testApp.zip?dl=0
我使用的是安卓导航组件,下面是应用截图:
如您所见,在 MainActivity 布局中,有一个 nav_host_fragment、一个工具栏和一个底部导航视图。
图中Blue Tab的顺序会是这样的
“CUSTOM TITLE HERE”工具栏中的标题硬编码在destination_blue1 片段中
但是当我从 blue1 移动到 blue2,然后使用后退按钮(物理硬件后退按钮)返回 blue1 时,标题会更改为“fragment_blue1”,而不是“CUSTOM TITLE HERE”(硬编码)。
"fragment_blue1" 实际上是该片段的目标图 id 字符串。
我不明白为什么即使我将标题硬编码为“CUSTOM TITLE HERE”,但如果我使用(物理硬件后退按钮)它就不起作用。
但如果我使用向上按钮(工具栏/操作栏中的后退按钮),那么标题将是“CUSTOM TITLE HERE”,根据我硬编码的标题。
这是当我的硬编码标题不起作用时的标题,当我使用后退按钮(物理后退按钮)从蓝色 2 移回蓝色 1 时。
这是我真实案例的简化,我需要从片段 Blue1 动态更改标题。我不明白为什么使用后退按钮后无法更改标题。但是当使用向上按钮时,标题将按照我使用的代码跟随,与目标ID图不同。
如何解决这个问题?出了什么问题?
我正在使用样式<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">,这是我的 MainActivity 的代码
class MainActivity : AppCompatActivity() {
lateinit var navController : NavController
lateinit var toolbar: Toolbar
lateinit var bottomNavigationView : BottomNavigationView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
navController = Navigation.findNavController(this,R.id.nav_host_fragment)
setUpViewDeclaration()
setupBottomNavMenu()
setupActionBar()
}
private fun setUpViewDeclaration() {
toolbar = findViewById(R.id.toolbar)
bottomNavigationView = findViewById(R.id.bottom_nav)
}
private fun setupBottomNavMenu() {
bottom_nav.setupWithNavController(navController)
}
private fun setupActionBar() {
// set up top hierarchy destination
val appBarConfiguration = AppBarConfiguration(setOf(
R.id.destination_blue1,
R.id.destination_red1)
)
setSupportActionBar(toolbar)
toolbar.setupWithNavController(navController,appBarConfiguration)
}
}
这是blue1片段的代码
class Blue1Fragment : Fragment() {
lateinit var moveButton: Button
lateinit var fragmentView: View
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
fragmentView = inflater.inflate(R.layout.fragment_blue1, container, false)
moveButton = fragmentView.findViewById(R.id.move_button_1)
// The title hard coded in here
// this one line below seems doesn't work if using back physical button
(activity as AppCompatActivity).supportActionBar?.title = "CUSTOM TITLE HERE"
moveButton.setOnClickListener {
val nextDestination = Blue1FragmentDirections.actionToBlue2()
Navigation.findNavController(fragmentView).navigate(nextDestination)
}
return fragmentView
}
}
这是blue2片段的代码:
class Blue2Fragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_blue2, container, false)
}
}
【问题讨论】:
标签: android android-architecture-components android-jetpack android-architecture-navigation android-jetpack-navigation