Android工具栏仅在AppBarLayout收集时显示标题和副标题

我有AppBarLayout,CollapsingToolbarLayout和工具栏的活动.

从代码中设置标题和副标题.最初我希望工具栏隐藏并在Appbar布局折叠时显示

我的代码工作(工具栏最初隐藏),但它始终显示工具栏标题和副标题.仅当appbar布局完全崩溃时,我如何显示标题

<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>

设置标题和副标题

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

《Android工具栏仅在AppBarLayout收集时显示标题和副标题》

最佳答案 一个简单的AppBarLayout.OnOffsetChangedListener应该只使用内置视图来实现:

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 : "");
        }
});

(此代码最初是用C#(Xamarin)编写的,而不是Java,因此可能需要进行少量修改)

点赞