【问题标题】:How can I get current theme's action bar background color?如何获取当前主题操作栏背景颜色?
【发布时间】:2014-05-17 06:43:37
【问题描述】:

我试图让导航抽屉的背景始终与操作栏的背景颜色匹配。

这样,每次,如果主题发生变化,两个背景都会自动变化。

我查看了R.attr,但没有找到任何东西。

【问题讨论】:

    标签: android android-actionbar background-color android-theme


    【解决方案1】:

    ActionBar API 无法检索当前背景 Drawable 或颜色。

    但是,您可以使用Resources.getIdentifier 调用View.findViewById,检索ActionBarView,然后调用View.getBackground 检索Drawable。即便如此,这仍然不会给你颜色。这样做的唯一方法是将Drawable 转换为Bitmap,然后使用某种color analyzer 来查找主色。

    这是一个检索ActionBar Drawable 的示例。

        final int actionBarId = getResources().getIdentifier("action_bar", "id", "android");
        final View actionBar = findViewById(actionBarId);
        final Drawable actionBarBackground = actionBar.getBackground();
    

    但似乎最简单的解决方案是创建您自己的属性并将其应用到您的主题中。

    这是一个例子:

    自定义属性

    <attr name="drawerLayoutBackground" format="reference|color" />
    

    初始化属性

    <style name="Your.Theme.Dark" parent="@android:style/Theme.Holo">
        <item name="drawerLayoutBackground">@color/your_color_dark</item>
    </style>
    
    <style name="Your.Theme.Light" parent="@android:style/Theme.Holo.Light">
        <item name="drawerLayoutBackground">@color/your_color_light</item>
    </style>
    

    然后在包含您的DrawerLayout 的布局中,像这样应用android:background 属性:

    android:background="?attr/drawerLayoutBackground"
    

    或者您可以使用TypedArray获取它

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        final TypedArray a = obtainStyledAttributes(new int[] {
                R.attr.drawerLayoutBackground
        });
        try {
            final int drawerLayoutBackground = a.getColor(0, 0);
        } finally {
            a.recycle();
        }
    
    }
    

    【讨论】:

    • actionBar.getBackground() 返回 null。我做错了吗?
    • @kalehv 你有使用 getActivity().getActionBar().setBackgroundDrawable(...) 设置的背景吗?如果设置了非,你确实会得到一个空值。
    猜你喜欢
    • 1970-01-01
    • 2020-04-21
    • 2012-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多