How can I get the current background color of the theme action bar?

I tried to make the background of my navigation background always match the background color of the action bar.

So, every time the theme changes, both backgrounds automatically change.

I looked at R.attr but found nothing.

+7
android background-color android-actionbar android-theme
source share
1 answer

The ActionBar API has no way to get the current Drawable background or color.

However, you can use Resources.getIdentifier to call View.findViewById , get an ActionBarView , and then call View.getBackground to retrieve the Drawable . However, this still will not give you color. The only way to do this is to convert Drawable to Bitmap , and then use some kind of color analyzer to find the dominant color.

Here is an example of extracting an ActionBar Drawable .

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

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

Here is an example of this:

Custom attribute

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

Initialize 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 containing your DrawerLayout , apply the android:background attribute as follows:

 android:background="?attr/drawerLayoutBackground" 

Or you can get it using 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(); } } 
+6
source share

All Articles