以编程方式设置稀松布颜色

时间:2015-11-13 17:04:56

标签: android material-design

我正在尝试以编程方式设置AppBarLayout的主要颜色。 XML布局是AndroidStudio的滚动示例:

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

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

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

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

在活动中,我希望AppBarLayout中的所有项目都有黄色背景,所以我设置:

int barColor = Color.parseColor("#FFC107");
AppBarLayout barLayout = (AppBarLayout) this.findViewById(R.id.app_bar);
if (barLayout != null) {
    barLayout.setBackgroundColor(barColor);
}
toolbar.setBackgroundColor(barColor);

CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout) this.findViewById(R.id.toolbar_layout);
if (collapsingToolbarLayout != null) {
    collapsingToolbarLayout.setBackgroundColor(barColor);
    collapsingToolbarLayout.setContentScrimColor(barColor);
}

一切正常,除非我滚动工具栏的中途(在FAB消失的确切位置)。在该状态下,工具栏的颜色仍然是默认的主要颜色(蓝色,而不是黄色),如下图所示:

enter image description here

所以,有两个问题:

  • 我错过了一个方法调用吗?
  • 有关调试这些方案的任何提示吗?在Android设备监视器的视图层次结构转储中,我无法分辨哪一个是用这种颜色着色的视图。

1 个答案:

答案 0 :(得分:16)

我遇到了同样的问题,你还必须设置statusBar稀松布颜色:

    int red = ContextCompat.getColor(activity, R.color.red);
    collapsingToolbar.setBackgroundColor(red);
    collapsingToolbar.setContentScrimColor(red);
    collapsingToolbar.setStatusBarScrimColor(red);

您甚至可以直接使用颜色获取颜色:

    collapsingToolbar.setBackgroundResource(R.color.red);
    collapsingToolbar.setContentScrimResource(R.color.red);
    collapsingToolbar.setStatusBarScrimResource(R.color.red);
相关问题