androidandroid-collapsingtoolbarlayout

Show CollapsingToolbarLayout title only when collapsed


I've tried setExpandedTitleColor and setCollapsedTitleColor (switching to and from transparent) with no luck. I can't see any built in methods that'll do what I'm looking for, either.

I only want to show the title when the CollapsingToolbarLayout is fully collapsed, otherwise, I need it hidden.

Any hints?


Solution

  • You can add OnOffsetChangedListener to AppBarLayout to determine when CollapsingToolbarLayout is collapsed or expanded and set it's title.

    Java

    final CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsingToolbarLayout);
    AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.appBarLayout);
    appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
        boolean isShow = true;
        int scrollRange = -1;
    
        @Override
        public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
            if (scrollRange == -1) {
                scrollRange = appBarLayout.getTotalScrollRange();
            }
            if (scrollRange + verticalOffset == 0) {
                collapsingToolbarLayout.setTitle("Title");
                isShow = true;
            } else if(isShow) {
                collapsingToolbarLayout.setTitle(" ");//careful there should a space between double quote otherwise it wont work 
                isShow = false;
            }
        }
    });
    

    Kotlin

    var isShow = true
    var scrollRange = -1
    appBarLayout.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { barLayout, verticalOffset ->
        if (scrollRange == -1){
            scrollRange = barLayout?.totalScrollRange!!
        }
        if (scrollRange + verticalOffset == 0){
            collapsingToolbarLayout.title = "Title Collapse"
            isShow = true
        } else if (isShow){
            collapsingToolbarLayout.title = " " //careful there should a space between double quote otherwise it wont work
            isShow = false
        }
    })