How to set title in app bar with Navigation Architecture Component

前端 未结 12 2016
面向向阳花
面向向阳花 2020-12-24 11:40

I was trying out Navigation architecture component and is now having difficulties in setting the title. How do I set the title programmatically and also how it works?

<
12条回答
  •  情话喂你
    2020-12-24 12:34

    Update title with either label in navigation xml or exclude labels and set with requiresActivity().title Supports mixing the two ways for screens with and without dynamic titles. Works for me with a Compose UI toolbar and Tabs.

        val titleLiveData = MutableLiveData()
        findNavController().addOnDestinationChangedListener { _, destination, _ ->
            destination.label?.let {
                titleLiveData.value = destination.label.toString()
            }
        }
    
        (requireActivity() as AppCompatActivity).setSupportActionBar(object: Toolbar(requireContext()) {
            override fun setTitle(title: CharSequence?) {
                titleLiveData.value = title.toString()
            }
        })
    
        titleLiveData.observe(viewLifecycleOwner, { 
            // Update your title
        })
    

提交回复
热议问题