Show CollapsingToolbarLayout title only when collapsed
Asked Answered
S

16

167

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?

Spirant answered 27/7, 2015 at 20:15 Comment(0)
A
322

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
    }
})
Alterant answered 22/9, 2015 at 18:37 Comment(11)
This solution works for api 23 and above. This is the most correct solution.Phosphate
Please mark this as the correct answer. The answer from @dlohani that is currently marked as correct does not hide the text because you can see it transition.Amick
this works for me, BUT I had to reset isShow and scrollRange whenever I update the contents of my layoutPalaeontology
byDefault app is coming in Collapsingbar, after collapsing and expanding this solutions works. but what to do if I don't want to get app name while activity starts?Maldon
It worked for me, but had to change "boolean isShow = false" to true to remove app name in expanded toolbar at activity start.Edee
what is the solution for api below 23 ?Bleier
@Giuseppe: it's the same. Tested on API 16 --> workingElsa
This didn't work for me, sometimes the title doesn't show up at all even when my logs clearly state that setTitle was called with "Title"Aton
Thanks, this works. But I get a better effect by if (scrollRange + verticalOffset <120). This will always have some text on the appbar instead of a empty appbar.Campobello
Thanks for your solution. I write in Kotlin this code collapsingToolbar.title = if (abs(verticalOffset) != appBarLayout.totalScrollRange) " " else "Title Collapse"Dong
How to achieve the same same functionality using Jetpack Compose? Any help will be appreciatedSwaim
B
50

I tried dlohani's solution, but didn't like it because of the fading out. With this solution, you remove the fading completely.

The trick is to create a new style with textSize equal to 0.1sp or 0sp (this one crashes on SDK < 19) and textColor transparent:

For SDK < 19

<style name="CollapsingToolbarLayoutExpandedTextStyle" parent="AppTheme">
    <item name="android:textColor">@android:color/transparent</item>
    <item name="android:textSize">0.1sp</item>
</style>

For SDK >= 19

<style name="CollapsingToolbarLayoutExpandedTextStyle" parent="AppTheme">
    <item name="android:textColor">@android:color/transparent</item>
    <item name="android:textSize">0sp</item>
</style>

Then apply it to the CollapsingToolbarLayout in your layout:

    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/collapsing_toolbar"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:expandedTitleTextAppearance="@style/CollapsingToolbarLayoutExpandedTextStyle"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">
Bushire answered 11/9, 2015 at 17:26 Comment(9)
Ok, like always, this is another solution that doesn't work the same for all devices. On Kitkat 0sp seems to work, but on Jellybean it makes the app crash. 0.1sp works on Jellybean but makes the text shaky on Kitkat :(Excrescency
How can we set that api level limit on the style?Craftsman
You need to use the values-v19 folder for SDK >= 19 and values folder for SDK < 19. Take a look at this for a reference: #16624817Excrescency
This seems to be the proper solution...the addOnOffsetChangedListener was added sometime later in the support library and also wasn't available on Xamarin :-PScissor
This works on N while the solution from @dlohani did notIlluminative
I used the 2nd code snippet for JellyBean and Marshmellow.It worked fine for both.Thnx..Carnation
This stops working after update to 'com.google.android.material:material:1.1.0'Chalutz
The problem persists: the text still fades gradually (which means that it will cover any other text shown) when the collapsing toolbar is collapsed.Entomb
0sp does not work because of if (textAppearance.textSize != 0) { expandedTextSize = textAppearance.textSize; } in com.google.android.material.internal.CollapsingTextHelper#setExpandedTextAppearance, also small size like 5sp makes nice disappear animationHeiser
I
41

I was able to get the desired effect by adding following property to the xml layout:

app:expandedTitleTextAppearance="@android:color/transparent"

so my CollapsingToolbarLayout looks like this

<android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/collapsingToolbarLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:expandedTitleTextAppearance="@android:color/transparent"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">
Irredeemable answered 28/7, 2015 at 7:21 Comment(9)
this is awsome :) is there any wey for title to come up with some animation ?Katowice
sorry, i have no idea yet for animating, if we do not hide the expanded title by changing appearance, it will be animated (size decreasing) by defaultIrredeemable
This is horrible, you see it fading in as its collapsing. Rather it just fade in in its final position.Erich
wirking fab but getting erroe in 4.2.2 width and height must be > 0Badgett
Ditto what CaptRisky said. Unfortunately, I don't think there's an alternative :-(Scissor
Thiswill only work if you are using the android api 22 or below. For 23 or above, the solution does not work. You will have to use the solution from @steven274.Phosphate
It's working even better while on android api 23 when I triedIrredeemable
I tried this, but the title still displayed though.Anthropophagite
worked only below api22, worked when created styles.xml as ruben suggested in api23Pyrophosphate
V
25

I have a more simple answer:

final CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.toolbar_layout);

collapsingToolbarLayout.setTitle("Your Title");
collapsingToolbarLayout.setExpandedTitleColor(getResources().getColor(R.color.transperent)); // transperent color = #00000000
collapsingToolbarLayout.setCollapsedTitleTextColor(Color.rgb(0, 0, 0)); //Color of your title

Happy Coding!

Voodoo answered 11/2, 2016 at 11:52 Comment(3)
This causes the same fade in issue as referenced in other answers.Amick
I only wanted to change the Toolbar title color and it worked for me with mCollapsingToolbarLayout.setExpandedTitleColor(Color.argb(255,0,0,0))Jato
@Bartosz Kosarzycki , I was unlucky with mCollapsingToolbarLayout.setExpandedTitleColor(Color.argb(255,0,0,0) ); but mCollapsingToolbarLayout.setExpandedTitleColor( context.getResources().getColor( android.R.color.transparent ) ); did the job, but certainly derives from your solution :)Nesbitt
S
24

This code works for me: Use color.parse color because if your background color is different then replace with white and your title not display

collapsingToolbarLayout.setExpandedTitleColor(Color.parseColor("#00FFFFFF"));

Or you can use for transparent collapsingToolbarLayout.setExpandedTitleColor(Color.TRANSPARENT);

Situla answered 13/3, 2017 at 14:1 Comment(0)
N
21

I successfully added a fading textview, simply add a text view in toolbar, and setting it's alpha based on the verticalOffset in appbar callback

mAppBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {

        @Override
        public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {

            mTitleTextView.setAlpha(Math.abs(verticalOffset / (float)
                    appBarLayout.getTotalScrollRange()));
        }
    });
Nadabb answered 5/8, 2016 at 20:44 Comment(1)
float range = appBarLayout.getTotalScrollRange(); float alpha = Math.abs(verticalOffset / range); if(alpha > 0.8) { mToolbar.setAlpha(alpha); } else { mToolbar.setAlpha(.0f); }Tova
C
14

Here the simplest and working solution also with api 23:

app:expandedTitleTextAppearance has to inherit TextAppearance.

So, in your styles.xml add this rows:

<style name="TransparentText" parent="@android:style/TextAppearance">
   <item name="android:textColor">#00000000</item>
</style>

Then, in your CollapsingToolbarLayout, add this row.

app:expandedTitleTextAppearance="@style/TransparentText"

That's all folks!

Cycling answered 30/6, 2016 at 22:49 Comment(0)
B
8

The below solution works perfectly.

appbar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
                @Override
                public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                    if (Math.abs(verticalOffset)-appBarLayout.getTotalScrollRange() == 0)
                    {
                        // Collapsed
                        setTitle("Title To Show");
                    }
                    else
                    {
                        // Expanded
                        setTitle("");
                    }
                }
            });
Bilge answered 12/4, 2018 at 6:36 Comment(0)
A
4

Here is my solution:

collapsingToolbar.setCollapsedTitleTextAppearance(R.style.personal_collapsed_title);
collapsingToolbar.setExpandedTitleTextAppearance(R.style.personal_expanded_title);

<style name="personal_collapsed_title">
     <item name="android:textSize">18sp</item>
     <item name="android:textColor">@color/black</item>
</style>

<style name="personal_expanded_title">
     <item name="android:textSize">0sp</item>
</style>
Artima answered 23/7, 2016 at 6:54 Comment(0)
E
4

just add this code :

     CollapsingToolbarLayout collapsingToolbarLayout = findViewById(R.id.collaps_main);

collapsingToolbarLayout.setExpandedTitleColor(ContextCompat.getColor(this , android.R.color.transparent));
Engstrom answered 21/5, 2020 at 14:50 Comment(0)
S
3

This works for me.

final Toolbar tool = (Toolbar)findViewById(R.id.toolbar);
CollapsingToolbarLayout c = (CollapsingToolbarLayout)findViewById(R.id.collapsing_toolbar);
AppBarLayout appbar = (AppBarLayout)findViewById(R.id.app_bar_layout);
tool.setTitle("");
setSupportActionBar(tool);
c.setTitleEnabled(false);

appbar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
    boolean isVisible = true;
    int scrollRange = -1;
    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
        if (scrollRange == -1) {
            scrollRange = appBarLayout.getTotalScrollRange();
        }
        if (scrollRange + verticalOffset == 0) {
           tool.setTitle("Title");
            isVisible = true;
        } else if(isVisible) {
            tool.setTitle("");
            isVisible = false;
        }
    }
});
Sulla answered 4/5, 2016 at 11:44 Comment(0)
G
2

In my oppinion a bit more elegant solution would be something like this.

public class MyCollapsingToolbarLayout extends CollapsingToolbarLayout {

    private final int toolbarId;
    @Nullable private Toolbar toolbar;

    public MyCollapsingToolbarLayout(Context context, AttributeSet attrs) {
        super(context, attrs);

        setTitleEnabled(false);

        TypedArray a = context.obtainStyledAttributes(attrs,
                R.styleable.CollapsingToolbarLayout, 0,
                R.style.Widget_Design_CollapsingToolbar);

        toolbarId = a.getResourceId(android.support.design.R.styleable.CollapsingToolbarLayout_toolbarId, -1);

        a.recycle();

    }

    @Override public void setScrimsShown(boolean shown, boolean animate) {
        super.setScrimsShown(shown, animate);

        findToolbar();
        if (toolbar != null) {
            toolbar.setTitleTextColor(shown ? Color.WHITE : Color.TRANSPARENT);
        }
    }

    private void findToolbar() {
        if (toolbar == null) {
            toolbar = (Toolbar) findViewById(toolbarId);
        }
    }

}

And usage would look something like this

<butter.droid.widget.BurtterCollapsingToolbarLayout
        app:toolbarId="@+id/toolbar"
        ...>

There is also a possibility to fade out/in text instead of just showing or hiding it.

Gulden answered 25/1, 2017 at 15:15 Comment(0)
P
1

This is kotlin version which works for me :

appbar.addOnOffsetChangedListener(object : OnOffsetChangedListener {
                var isShow = true
                var scrollRange = -1
                override fun onOffsetChanged(appBarLayout: AppBarLayout, verticalOffset: Int) {
                    if (scrollRange == -1) scrollRange = appBarLayout.totalScrollRange

                    if (scrollRange + verticalOffset == 0) {
                        toolbarLayout.title = "Title"
                        isShow = true
                    } else if (isShow) {
                        toolbarLayout.title = " " //These quote " " with _ space is intended 
                        isShow = false
                    }
                }
            })
Pliant answered 2/1, 2020 at 3:22 Comment(0)
A
0

Kotlin extension:

fun AppBarLayout.onAppBarLayoutCollapsed(
  isShowing: (isShow: Boolean) -> Unit
) {
  var isShow: false
  var scrollRange = -1
  this.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { barLayout, verticalOffset ->
    if (scrollRange == -1) {
      scrollRange = barLayout?.totalScrollRange!!
    }
    isShow = scrollRange + verticalOffset == 0
    isShowing.invoke(isShow)
  })

and after that:

appBarLayout.onAppBarLayoutCollapsed({
   if(it){
     ///set text
   }else{
     ///remove text
   }
})

Amity answered 17/2, 2022 at 15:56 Comment(0)
E
0

Here the easiest and performant way to hide title in appbar when your CollapsingToolbarLayout is expanded

First method

First add app:expandedTitleTextColor="@android:color/transparent" to collapssingToolbar, so our title won't show until collapsed

<com.google.android.material.appbar.CollapsingToolbarLayout
...
app:expandedTitleTextColor="@android:color/transparent"
/>

Second add java code, so we will show this title in appbar

mCollapsingToolbarLayout.setTitleEnabled(true);

You are done.

And don't ever use addOnOffsetChangedListener to setTitle to empty string and title, because you will be flooded with

requestLayout() improperly called by androidx.appcompat.widget.AppCompatTextView{d67976 V.ED..... ........ 252,51-936,144} during second layout pass: posting in next frame

First method can show slightly seen transparent text, so we can make size of text 0.1 to make it hidden

Second method

add style

<style name="CollapsingToolbarLayoutExpandedTextStyle">
        <item name="android:textColor">@android:color/transparent</item>
        <item name="android:textSize">0.1sp</item>
</style>

add property to xml

<com.google.android.material.appbar.CollapsingToolbarLayout
...
app:expandedTitleTextAppearance="@style/CollapsingToolbarLayoutExpandedTextStyle"
/>
mCollapsingToolbarLayout.setTitleEnabled(true);
Eyespot answered 14/6, 2023 at 19:18 Comment(0)
S
0

The only valid solution for me right now (min SDK 23), using Material3 as base app theme is similar to this answer, but instead of using expandedTitleTextAppearance, using:

app:expandedTitleTextColor="@android:color/transparent"

So that the CollapsingToolbarLayout remains like this:

    <com.google.android.material.appbar.CollapsingToolbarLayout
        android:id="@+id/collapsing_toolbar"
        android:layout_width="match_parent"
        android:layout_height="256dp"
        android:fitsSystemWindows="true"
        app:expandedTitleTextColor="@android:color/transparent"
        app:contentScrim="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|exitUntilCollapsed"
        style="@style/Widget.Material3.CollapsingToolbar.Large" >

When collapsed, the title color will be the one defined by default in the Material3 base theme

Sofiasofie answered 27/6, 2023 at 10:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.