Search code examples
androidandroid-collapsingtoolbarlayoutandroid-architecture-navigation

How to use with CollapsingLayout with Navigation Advanced Example


I am trying to integrate Collapsing layout with Navigation Advanced example

What I tried?

Added Collapsing bar layout to main_actvity.xml

<com.google.android.material.appbar.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <com.google.android.material.appbar.CollapsingToolbarLayout
        android:id="@+id/collapsing_toolbar_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"/>

    </com.google.android.material.appbar.CollapsingToolbarLayout>

</com.google.android.material.appbar.AppBarLayout>

Modified setupBottomNavigationBar() in MainActivity.kt

private fun setupBottomNavigationBar(){

...
controller.observe(this, Observer { navController ->

            mainBinding.collapsingToolbarLayout.setupWithNavController(mainBinding.toolbar, navController)
            //setupActionBarWithNavController(navController)
        })
...
}

Current issue:

Now I have two ActionBars instead of one. Top one have app name as the title, one below shows nothing initially but when navigated to an sub destination only a grey back arrow is shown, no destination label is shown on the actionbar

Anyone who understand this multiple backstack implementation, please help me to get things work with CollapsingToolbarLayout

Update:

Got rid of one action bar as @Manoj suggested in a comment, Now need to fix not appearing of titles in the actionbar

Update 2:

Although the destination labels(titles) are not shown when navigated to sub destinations, but back button is shown.


Solution

  • I finally figured out why the toolbar title was not shown reason was I have not set enough height for appbar layout, I was using wrap_content so collapsing toolbar layout was covering the toolbar title. Solution was to set appbar layout height to value larger than 64dp. When I increased the appbar layout height, it looks unusually tall. (Forgive me for my lack of understanding of how collapsing toolbar works)

    But this was not my intention, I wanted to enable collapsing toolbar for some specific fragments, I was using single activity concepts as navigation architecture component recommends.

    As I read in following answers

    1. Having two toolbars and making one transparent when doing fragment transactions.
    2. Having separate toolbar for each fragment

    IMHO Both of these are not good solutions if you are using navigation architecture component, there is no value of using navigation architecture component, if you need to manage fragment transactions or toolbars manually.

    So for now I have stop using collapsing toolbar.