如何获取当前主题的操作栏背景颜色?

10
我试图让我的导航抽屉背景始终与操作栏背景颜色相匹配。这样,每次主题更改时,两个背景都会自动更改。我查看了R.attr,但没有找到任何内容。
1个回答

6
ActionBar API没有一种方法来检索当前的背景Drawable或颜色。但是,您可以使用Resources.getIdentifier调用View.findViewById,检索ActionBarView,然后调用View.getBackground来检索Drawable。即使这样,这仍然无法给您颜色。唯一的方法是将Drawable转换为Bitmap,然后使用某种颜色分析器查找主要颜色。
以下是检索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();
    }

}

4
actionBar.getBackground() 返回 null。我做错了什么吗? - Harshad Kale
@kalehv,你是否使用了getActivity().getActionBar().setBackgroundDrawable(...)来设置背景?如果没有设置,你确实会得到一个null值。 - hcpl

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接