Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android toolbar show title and subtitle only when AppBarLayout collepsed

I have activity with AppBarLayout ,CollapsingToolbarLayout and toolbar. Setting title and subtitle from code. Initially i want toolbar hidden and show when Appbar layout collapsed, With my code its working (toolbar hide initially) but its showing toolbar title and subtitle always. How do i show title only when appbar layout collapse completely

<android.support.design.widget.AppBarLayout
    android:id="@+id/app_bar"
    android:layout_width="match_parent"
    android:layout_height="@dimen/app_bar_height"
    android:fitsSystemWindows="true"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/toolbar_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        app:titleEnabled="false"
        app:contentScrim="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_collapseMode="pin"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>

Setting title and subtitle

 Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowHomeEnabled(true);
    getSupportActionBar().setTitle("Title");
    getSupportActionBar().setSubtitle("sutitle");

enter image description here

like image 473
user rd Avatar asked Oct 30 '22 10:10

user rd


1 Answers

A simple AppBarLayout.OnOffsetChangedListener should do the trick using only built-in views:

AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.app_bar);
appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener {
    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int offset) {
            ActionBar actionBar = getSupportActionBar();
            boolean toolbarCollapsed = Math.abs(offset) >= appBarLayout.getTotalScrollRange();
            actionBar.setTitle(toolbarCollapsed ? yourTitle : "");
            actionBar.setSubtitle(toolbarCollapsed ? yourSubTitle : "");
        }
});

(This code originally was written in C# (Xamarin), not Java, so minor modifications may be needed)

like image 179
Daniel Veihelmann Avatar answered Nov 08 '22 06:11

Daniel Veihelmann