How to set title in app bar with Navigation Architecture Component

前端 未结 12 1988
面向向阳花
面向向阳花 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:24

    It's actually because of:

    android:label="fragment_main"
    

    Which you have set in the xml.

    So what is the proper way to show the title for Fragments using Navigation Component?

    setTitle() works at this point. But, because you set label for those Fragments, it might show the label again when recreating the Activity. The solution will probably be deleting android:label and then do your things with code:

    ((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("your title");
    

    Or:

    ((AppCompatActivity) getActivity()).getSupportActionBar().setSubtitle("your subtitle");
    

    In onCreateView().


    Found a workaround:

    interface TempToolbarTitleListener {
        fun updateTitle(title: String)
    }
    
    class MainActivity : AppCompatActivity(), TempToolbarTitleListener {
    
        ...
    
        override fun updateTitle(title: String) {
            binding.toolbar.title = title
        }
    }
    

    Then:

    (activity as TempToolbarTitleListener).updateTitle("custom title")
    

    Check this out too:Dynamic ActionBar title from a Fragment using AndroidX Navigation

提交回复
热议问题