How can I get current theme's action bar background color?
Asked Answered
R

1

10

I was trying to make my navigation drawer's background always match with the action bar's background color.

So that, every time, if the theme changes both background will change automatically.

I looked into R.attr, but didn't find anything.

Rodin answered 4/4, 2014 at 19:28 Comment(0)
T
6

The ActionBar API doesn't have a way to retrieve the current background Drawable or color.

However, you could use Resources.getIdentifier to call View.findViewById, retrieve the ActionBarView, then call View.getBackground to retrieve the Drawable. Even so, this still won't give you the color. The only way to do that would be to convert the Drawable into a Bitmap, then use some sort of color analyzer to find the dominant color.

Here's an example of retrieving the ActionBar Drawable.

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

But it seems like the easiest solution would be to create your own attribute and apply it in your themes.

Here's an example of that:

Custom attribute

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

Initialize the attribute

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

Then in the layout that contains your DrawerLayout, apply the android:background attribute like this:

android:background="?attr/drawerLayoutBackground"

Or you can obtain it using a 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();
    }

}
Therine answered 4/4, 2014 at 20:56 Comment(2)
actionBar.getBackground() returns me null. Am I doing something wrong?Erkan
@kalehv do you have a background set using getActivity().getActionBar().setBackgroundDrawable(...) ? If non is set you would indeed get a null value.Anishaaniso

© 2022 - 2024 — McMap. All rights reserved.