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.
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.
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();
}
}
© 2022 - 2024 — McMap. All rights reserved.