Как изменить цвет actionbar android studio

I am using Android Navigation bar in my project, I want to change the top color in action bar to something red, How can i do that? I have something like this, and i want something like this, how ...

In general Android OS leverages a “theme” to allow app developers to globally apply a universal set of UI element styling parameters to Android applications as a whole, or, alternatively, to a single Activity subclass.

So there are three mainstream Android OS “system themes,” which you can specify in your Android Manifest XML file when you are developing apps for Version 3.0 and later versions

I am referring the (APPCOMPAT)support library here:—
So the three themes are
1. AppCompat Light Theme (Theme.AppCompat.Light)

enter image description here

  1. AppCompat Dark Theme(Theme.AppCompat),

enter image description here

  1. And a hybrid between these two ,AppCompat Light Theme with the Darker ActionBar.( Theme.AppCompat.Light.DarkActionBar)

AndroidManifest.xml and see the tag, the android theme is mentioned as:— android:theme=»@style/AppTheme»

Open the Styles.xml and we have base application theme declared there:—

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
  </style>

We need to override these parent theme elements to style the action bar.

ActionBar with different color background:—

To do this we need to create a new style MyActionBar(you can give any name) with a parent reference to @style/Widget.AppCompat.Light.ActionBar.Solid.Inverse that holds the style characteristics for the Android ActionBar UI element. So definition would be

<style name="MyActionBar" parent="@style/Widget.AppCompat.Light.ActionBar.Solid.Inverse">
    <item name="background">@color/red</item>
</style>

And this definition we need to reference in our AppTheme, pointing to overridden ActionBar styling as—

@style/MyActionBar
ActionBar with pink background color

Change the title bar text color (e.g black to white):—

Now to change the title text color, we need to override the parent reference parent=»@style/TextAppearance.AppCompat.Widget.ActionBar.Title»>

So the style definition would be

<style name="MyActionBarTitle" parent="@style/TextAppearance.AppCompat.Widget.ActionBar.Title">
    <item name="android:textColor">@color/white</item>
</style>

We’ll reference this style definition inside the MyActionBar style definition, since the TitleTextStyle modification is a child element of an ActionBar parent OS UI element. So the final definition of MyActionBar style element will be

<style name="MyActionBar" parent="@style/Widget.AppCompat.Light.ActionBar.Solid.Inverse">
    <item name="background">@color/red</item>
    <item name="titleTextStyle">@style/MyActionBarTitle</item>
</style>

SO this is the final Styles.xml

<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light">
        <!-- This is the styling for action bar -->
        <item name="actionBarStyle">@style/MyActionBar</item>
    </style>

    <style name="MyActionBar" parent="@style/Widget.AppCompat.Light.ActionBar.Solid.Inverse">
        <item name="background">@color/red</item>
        <item name="titleTextStyle">@style/MyActionBarTitle</item>
    </style>

    <style name="MyActionBarTitle" parent="@style/TextAppearance.AppCompat.Widget.ActionBar.Title">
        <item name="android:textColor">@color/white</item>
    </style>
</resources>

ActionBar With white title color
For further ActionBar options Menu styling, refer this link

Improve Article

Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    In this article, you will learn how to change the colour of the Action Bar in an Android App.

    There are two ways to change color.

    1. By changing styles.xml file:
      • Just go to res/values/styles.xml file
      • edit the xml file to change the color of action bar.
      • Code for styles.xml is given below

      styles.xml

      <resources>

          <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

              <item name="colorPrimary">#0F9D58</item>

              <item name="colorPrimaryDark">@color/colorPrimaryDark</item>

              <item name="colorAccent">@color/colorAccent</item>

          </style>

          <style name="AppTheme.NoActionBar">

              <item name="windowActionBar">false</item>

              <item name="windowNoTitle">true</item>

          </style>

          <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

          <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

      </resources>

      activity_main.xml

      <?xml version="1.0" encoding="utf-8"?>

      <RelativeLayout

          android:layout_width="match_parent"

          android:layout_height="match_parent"

          android:id="@+id/relativelayout">

         <TextView

             android:layout_width="wrap_content"

             android:layout_height="wrap_content"

             android:id="@+id/textview"

             android:textColor="#0F9D58"

             android:textSize="32dp"

             android:layout_centerInParent="true"/>

      </RelativeLayout>

      MainActivity.java

      package com.geeksforgeeks.changecolor;

      import android.widget.TextView;

      import android.support.v7.app.AppCompatActivity;

      public class MainActivity extends AppCompatActivity {

          @Override

          protected void onCreate(Bundle savedInstanceState)

          {

              super.onCreate(savedInstanceState);

              setContentView(R.layout.activity_main);

              TextView t = findViewById(R.id.textview);

              t.setText("Geeks for Geeks");

          }

      }

    2. Through Java file by defining ActionBar object:
      • Define object for ActionBar and colorDrawable class
      • set color using setBackgroundDrawable function with colorDrawable object as its parameter.
      • Here is complete code for MainActivity.java

      MainActivity.java

      package com.geeksforgeeks.changecolor;

      import android.support.v7.app.ActionBar;

      import android.graphics.Color;

      import android.graphics.drawable.ColorDrawable;

      import android.support.v7.app.AppCompatActivity;

      public class MainActivity extends AppCompatActivity {

          @Override

          protected void onCreate(Bundle savedInstanceState)

          {

              super.onCreate(savedInstanceState);

              setContentView(R.layout.activity_main);

              ActionBar actionBar;

              actionBar = getSupportActionBar();

              ColorDrawable colorDrawable

                  = new ColorDrawable(Color.parseColor("#0F9D58"));

              actionBar.setBackgroundDrawable(colorDrawable);

          }

      }

      activity_main.xml

      <?xml version="1.0" encoding="utf-8"?>

      <RelativeLayout 

          android:layout_width="match_parent"

          android:layout_height="match_parent"

          android:id="@+id/relativelayout">

         <TextView

             android:layout_width="wrap_content"

             android:layout_height="wrap_content"

             android:textColor="#0F9D58"

             android:textSize="30dp"

             android:text="Geeks for Geeks"

             android:layout_centerInParent="true"/>

      </RelativeLayout>

    Output:

    • Default color of action Bar:
    • In Main Activity color of Action Bar is changed to hash code defined in above code.

    Статья является переводом топика из блога android-developers. В ней показывается, как стилизовать ActionBar нужным вам образом. В качестве примера рассматривается изменение оформления под общую цветовую гамму вышеописанного блога.

    Использование общепринятого элемента навигации ActionBar упрощает освоение программы пользователем, и не требует от разработчика придумывать свои собственные «велосипеды». Но раз уж все используют один и тот же паттерн, то, ясное дело, каждый стилизует его под своё приложение. Следующий пример показывает, как стилизовать Action Bar под общий вид приложения. Будем изменять стандартную тему оформления Holo.Light для соответствия блогу android-developers.

    
    <style name="Theme.AndroidDevelopers" parent="android:style/Theme.Holo.Light">
    …
    </style>
    

    Значок

    Для создания значка в выбранной цветовой схеме можно использовать Android Asset Studio. Будем использовать это изображение, как логотип.

    image

    Навигация

    Секция навигации работает в трёх разных режимах. Рассмотрим их по очереди.

    Стандартный

    Стандартный режим просто отображает название Activity. Для этого стилизация не нужна, поехали дальше.

    Список

    Слева — стандартный выпадающий список, справа — тот эффект, который нам нужен.

    image

    В стандартном списке используется цветовая схема, в которой доминирует голубой цвет. Чтобы реализовать нужную нам схему, перегрузим android:actionDropDownStyle

    
    <!-- стиль для списка -->
    <style name="MyDropDownNav" parent="android:style/Widget.Holo.Light.Spinner.DropDown.ActionBar">
        <item name="android:background">@drawable/ad_spinner_background_holo_light</item>
        <item name="android:popupBackground">@drawable/ad_menu_dropdown_panel_holo_light</item>
        <item name="android:dropDownSelector">@drawable/ad_selectable_background</item>
    </style>
    

    В этом xml-файле для оформления подсветки, Spinner и верхней панели используется комбинация state-list’ов и nine-patch изображений.

    Вкладки

    Ниже расположены скриншоты оформления вкладок «до» и «после».

    image

    И снова, в стандартной тема для вкладок доминирует голубой цвет. Для переоформления перегрузим android:actionBarTabStyle.

    
    <!-- стиль для вкладок -->
    <style name="MyActionBarTabStyle" parent="android:style/Widget.Holo.Light.ActionBarView_TabView">
        <item name="android:background">@drawable/actionbar_tab_bg</item>
        <item name="android:paddingLeft">32dp</item>
        <item name="android:paddingRight">32dp</item>
    </style>
    

    Действия (Actions)

    И снова, «до» и «после».

    image

    При выделении того или иного, элемента он подсвечивается голубым. Для изменения, перегрузим android:selectableItemBackground

    
    <item name="android:selectableItemBackground">@drawable/ad_selectable_background</item>
    

    Также, меню при расширении показывает голубой прямоугольник наверху списка. Для изменения перегрузим android:popupMenuStyle.

    
    <!-- стиль для меню -->
    <style name="MyPopupMenu" parent="android:style/Widget.Holo.Light.ListPopupWindow">
        <item name="android:popupBackground">@drawable/ad_menu_dropdown_panel_holo_light</item> 
    </style>
    

    Также изменим цвет выделенных элементов в меню.

    
    <!-- стиль для элементов внутри меню -->
    <style name="MyDropDownListView" parent="android:style/Widget.Holo.ListView.DropDown">
        <item name="android:listSelector">@drawable/ad_selectable_background</item>
    </style>
    

    Кроме этого еще нужно изменить оформление флажков и радиокнопок.

    
    <item name="android:listChoiceIndicatorMultiple">@drawable/ad_btn_check_holo_light</item>
    <item name="android:listChoiceIndicatorSingle">@drawable/ad_btn_radio_holo_light</item>
    

    image

    Фон

    В принципе, можно также изменить фон. По умолчанию, в теме Holo.Light он прозрачный. Для изменения нужно перегрузить android:actionBarStyle.

    Соединяем всё вместе

    Для объединения всех элементов, создадим кастомный стиль.

    
    <style name="Theme.AndroidDevelopers" parent="android:style/Theme.Holo.Light">
        <item name="android:selectableItemBackground">@drawable/ad_selectable_background</item>
        <item name="android:popupMenuStyle">@style/MyPopupMenu</item>
        <item name="android:dropDownListViewStyle">@style/MyDropDownListView</item>
        <item name="android:actionBarTabStyle">@style/MyActionBarTabStyle</item>
        <item name="android:actionDropDownStyle">@style/MyDropDownNav</item>
        <item name="android:listChoiceIndicatorMultiple">@drawable/ad_btn_check_holo_light</item>
        <item name="android:listChoiceIndicatorSingle">@drawable/ad_btn_radio_holo_light</item>
    </style>
    

    Теперь можно применять этот стиль оформления к какому-либо Activity или всему приложению.

    
    <activity android:name=".MainActivity" 
        android:label="@string/app_name"
        android:theme="@style/Theme.AndroidDevelopers"
        android:logo="@drawable/ad_logo">
    

    Важно еще отметить, что некоторые стили, которые мы перегрузили, действуют на все виджеты (например android:selectableItemBackground). То есть, мы таким образом изменяем оформление всего приложения, что бывает весьма полезно, если вы стараетесь выдержать общий стиль.<

    Исходник сэмпла можно взять на code.google.com.

    Источник: Кастомизация виджета Action Bar

    Полезные ссылки

    Реклама

    imageСтатья является переводом топика из блога android-developers. В ней показывается, как стилизовать виджет Action Bar нужным вам образом. В качестве примера рассматривается изменение оформления виджета под общую цветовую гамму вышеописанного блога.

    Со времени появления паттерна Action Bar прошло уже немало времени, и многие разработчики уже внедрили его в свои приложения. В Android 3.0 (Honeycomb) данный паттерн вообще является частью SDK и общей навигационной парадигмы. Использование общепринятого элемента навигации упрощает освоение программы пользователем (потому что он, скорее всего, уже работал с ним), и не требует от разработчика придумывать свои собственные «велосипеды». Но раз уж все используют один и тот же паттерн, то, ясное дело, каждый стилизует его под своё приложение. Следующий пример показывает, как стилизовать Action Bar под общий вид/имидж приложения. Будем изменять стандартную тему оформления Holo.Light для соответствия блогу android-developers.

    <style name="Theme.AndroidDevelopers" parent="android:style/Theme.Holo.Light">
    …
    </style>
    

    Иконка

    Для создания иконки в выбранной цветовой схеме можно использовать Android Asset Studio. Будем использовать это изображение, как логотип.

    image

    Навигация

    Далее, секция навигации работает в трёх разных режимах. Рассмотрим их по очереди.

    Стандартный

    Стандартный режим просто отображает название Activity. Для этого стилизация не нужна, поехали дальше.

    Список

    Слева — стандартный выпадающий список, справа — тот эффект, который нам нужен.

    image

    В стандартном списке используется цветовая схема, в которой доминирует голубой цвет. Чтобы реализовать нужную нам схему, перегрузим android:actionDropDownStyle

    <!-- стиль для списка -->
    <style name="MyDropDownNav" parent="android:style/Widget.Holo.Light.Spinner.DropDown.ActionBar">
        <item name="android:background">@drawable/ad_spinner_background_holo_light</item>
        <item name="android:popupBackground">@drawable/ad_menu_dropdown_panel_holo_light</item>
        <item name="android:dropDownSelector">@drawable/ad_selectable_background</item>
    </style>
    

    В этом xml-файле для оформления подсветки, спиннера и верхнего bar’a используется комбинация state-list’ов и nine-patch изображений.

    Вкладки

    Ниже расположены скриншоты оформления вкладок «до» и «после».

    image

    И снова, в стандартной тема для вкладок доминирует голубой цвет. Для переоформления перегрузим android:actionBarTabStyle.

    <!-- стиль для вкладок -->
    <style name="MyActionBarTabStyle" parent="android:style/Widget.Holo.Light.ActionBarView_TabView">
        <item name="android:background">@drawable/actionbar_tab_bg</item>
        <item name="android:paddingLeft">32dp</item>
        <item name="android:paddingRight">32dp</item>
    </style>
    

    Действия (Actions)

    И снова, «до» и «после».
    image

    При выделении того или иного, элемента он подсвечивается голубым. Для изменения, перегрузим android:selectableItemBackground.

    <item name="android:selectableItemBackground">@drawable/ad_selectable_background</item>
    

    Также, меню при расширении показывает голубой прямоугольник наверху списка. Для изменения перегрузим android:popupMenuStyle.

    <!-- стиль для меню -->
    <style name="MyPopupMenu" parent="android:style/Widget.Holo.Light.ListPopupWindow">
        <item name="android:popupBackground">@drawable/ad_menu_dropdown_panel_holo_light</item> 
    </style>
    

    Также изменим цвет выделенных элементов в меню.

    <!-- стиль для элементов внутри меню -->
    <style name="MyDropDownListView" parent="android:style/Widget.Holo.ListView.DropDown">
        <item name="android:listSelector">@drawable/ad_selectable_background</item>
    </style>
    

    Кроме этого еще нужно изменить оформление чекбоксов и radio buttons.

    <item name="android:listChoiceIndicatorMultiple">@drawable/ad_btn_check_holo_light</item>
    <item name="android:listChoiceIndicatorSingle">@drawable/ad_btn_radio_holo_light</item>
    

    image

    Фон

    В принципе, можно также изменить фон. По умолчанию, в теме Holo.Light он прозрачный. Для изменения нужно перегрузить android:actionBarStyle.

    Соединяем всё вместе

    Для объединения всех элементов, создадим кастомный стиль.

    <style name="Theme.AndroidDevelopers" parent="android:style/Theme.Holo.Light">
        <item name="android:selectableItemBackground">@drawable/ad_selectable_background</item>
        <item name="android:popupMenuStyle">@style/MyPopupMenu</item>
        <item name="android:dropDownListViewStyle">@style/MyDropDownListView</item>
        <item name="android:actionBarTabStyle">@style/MyActionBarTabStyle</item>
        <item name="android:actionDropDownStyle">@style/MyDropDownNav</item>
        <item name="android:listChoiceIndicatorMultiple">@drawable/ad_btn_check_holo_light</item>
        <item name="android:listChoiceIndicatorSingle">@drawable/ad_btn_radio_holo_light</item>
    </style>
    

    Теперь можно применять этот стиль оформления к какому-либо Activity или всему приложению.

    
    <activity android:name=".MainActivity" 
              android:label="@string/app_name"
              android:theme="@style/Theme.AndroidDevelopers"
              android:logo="@drawable/ad_logo">
    

    Важно еще отметить, что некоторые стили, которые мы перегрузили, действуют на все виджеты (например android:selectableItemBackground). То есть, мы таким образом изменяем оформление всего приложения, что бывает весьма полезно, если вы стараетесь выдержать общий стиль.

    Конец

    Исходник сэмпла можно взять на code.google.com.

    Так бывает складывается что нужно поменять полностью цвет Action bar’a, табов под ним и меню, да и всего на свете. Так вот это оказывается не так то просто (: Я проковырялся дня два пока разобрался со всем этим, и вот сегодня я хочу вам рассказать как да что нужно сделать что бы изменить цвет Action bar’a, табов и popup menu.

    Менять мы будем на синий цвет но для начала я хочу вам рассказать о таком замечательном ресурсе который позволяет одним махом заменить все и сразу, он называется Android Action Bar Style Generator, с его помощью вы можете создать нужный вам стиль, и скачать его. После вам остается только распаковать в нужные папки все файлы которые там есть и заменить стиль в манифесте на созданный вами… И все, дальше андроид сам подхватит этот стиль и будет его использовать как дефолтный.

    <application
            android:allowBackup="true"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/MY_SAMPLE_THEME_HERE" >
    

    Ну а теперь перейдем к моему варианту того как я менял цвет. 

    Для начала создадим файл res/values/color.xml в котором будем хранить все нужные нам коды цветов.

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
    
        <color name="actionbar_color">#314e6e</color>
        <color name="tabs_color">#2a4562</color>
        <color name="item_selected">#2a4562</color>
    
    </resources>
    

    ActionBar

    Для того что бы изменить цвет Action bar’a, вам нужно создать в файле res/values/style.xml, подгруппу в которой переопределим наш цвет. Для начала посмотрим как выглядит не тронутый style.xml.

    <resources xmlns:android="http://schemas.android.com/apk/res/android">
    
        <!--
            Base application theme, dependent on API level. This theme is replaced
            by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
        -->
        <style name="AppBaseTheme" parent="Theme.AppCompat.Light">
            <!--
                Theme customizations available in newer API levels can go in
                res/values-vXX/styles.xml, while customizations related to
                backward-compatibility can go here.
            -->
        </style>
    
    <!-- Application theme. -->
        <style name="AppTheme" parent="AppBaseTheme">
    
        </style>
    </resources>
    

    Что тут можно сказать… Ничего (: Так выглядит стандартный стиль темы в андроиде, для того что бы изменить цвет мы добавляем новый стиль:

    <style name="ActionBar" parent="Widget.AppCompat.Light.ActionBar.Solid.Inverse">
            <item name="android:background">@color/actionbar_color</item>
        </style>
    

    Таким образом мы задаем что фон у экшен бара будет нашего цвета тобиш синего.
    Теперь нам нужно задать этот стиль экшен бару по дефолту, для этого в AppTheme пишем следующее:

    <style name="AppTheme" parent="AppBaseTheme">
        <item name="android:actionBarStyle">@style/ActionBar</item>
    </style>
    

    Компилируем и смотрим что получилось, если ActionBar покрасился в выбранный нами цвет то вы все сделали правильно.

    Что получилось:

    Конечный вид:

    <resources xmlns:android="http://schemas.android.com/apk/res/android">
        <style name="AppBaseTheme" parent="Theme.AppCompat.Light">
        </style>
    
        <style name="AppTheme" parent="AppBaseTheme">
          <item name="android:actionBarStyle">@style/ActionBar</item>
        </style>
        
        <style name="ActionBar" parent="Widget.AppCompat.Light.ActionBar.Solid.Inverse">
            <item name="android:background">@color/actionbar_color</item>
            <item name="android:backgroundStacked">@color/tabs_color</item>
        </style>
    </resources>
    
    

    TabView

    Для того что бы подкрасить табы в нужный нам цвет достаточно просто добавить еще одну строчку в стиль ActionBar.

    <style name="ActionBar" parent="Widget.AppCompat.Light.ActionBar.Solid.Inverse">
            <item name="android:background">@color/actionbar_color</item>
            
            <!-- вот она ниже -->
            <item name="android:backgroundStacked">@color/tabs_color</item>
        </style>
    

    Теперь табы будут того цвета которого вы задали для пол tabs_color в файле colors.xml. 

    Что получилось:

    Конечный вид:

    <resources xmlns:android="http://schemas.android.com/apk/res/android">
        <style name="AppBaseTheme" parent="Theme.AppCompat.Light">
        </style>
    
        <style name="AppTheme" parent="AppBaseTheme">
          <item name="android:actionBarStyle">@style/ActionBar</item>
        </style>
        
        <style name="ActionBar" parent="Widget.AppCompat.Light.ActionBar.Solid.Inverse">
            <item name="android:background">@color/actionbar_color</item>
            <item name="android:backgroundStacked">@color/tabs_color</item>
        </style>
    </resources>
    

    Popup Menu

    С меню оказалось все немного сложнее чем я думал, сходу сделаться оно нужного мне цвета не хотелось поэтому я начал перебирать исходник стиля с сайта что я указал в начале статьи, ведь у них получилось, почему у меня не получается, и все таки нашел где же это делается.

    Создаем новый стиль и указываем в нем цвет

    <style name="PopupMenu" parent="@android:style/Widget.Holo.ListPopupWindow">
            <item name="android:popupBackground">@color/actionbar_color</item> 
        </style>
    

    Далее описываем его в AppTheme стиле который мы используем как родительский.

    <style name="AppTheme" parent="AppBaseTheme">
          <item name="android:actionBarStyle">@style/ActionBar</item>
          <item name="android:popupMenuStyle">@style/PopupMenu</item>
        </style>
    

    Но это еще не все, для того что бы этот стиль применялся нам нужно описать еще один дочерний стиль который будет задавать стиль конкретно для меню.

    <style name="Theme.stylingactionbar.widget" parent="@android:style/Theme.Holo">
            <item name="android:popupMenuStyle">@style/PopupMenu</item>
        </style>
    

    Что получилось:

    Конечный вид:

    <resources xmlns:android="http://schemas.android.com/apk/res/android">
        <style name="AppBaseTheme" parent="Theme.AppCompat.Light">
        </style>
    
        <style name="AppTheme" parent="AppBaseTheme">
          <item name="android:actionBarStyle">@style/ActionBar</item>
          <item name="android:popupMenuStyle">@style/PopupMenu</item>
          <item name="android:actionBarWidgetTheme">@style/Theme.stylingactionbar.widget</item>
        </style>
        
        <style name="ActionBar" parent="Widget.AppCompat.Light.ActionBar.Solid.Inverse">
            <item name="android:background">@color/actionbar_color</item>
            <item name="android:backgroundStacked">@color/tabs_color</item>
        </style>
        
        <style name="PopupMenu" parent="@android:style/Widget.Holo.ListPopupWindow">
            <item name="android:popupBackground">@color/actionbar_color</item> 
        </style>
        
        <style name="Theme.stylingactionbar.widget" parent="@android:style/Theme.Holo">
            <item name="android:popupMenuStyle">@style/PopupMenu</item>
        </style>
    </resources>
    

    Вот собственно и все что я хотел рассказать, для меня лично это оказалось проблемой по этому я решил описать ее решение сюда, может кому пригодится, а может сам забуду и буду по ней вспоминать что да как (:

    Details:

    I’m extending ActionBarActivity.
    Eclipse and SDK fully patched as of 2011-11-06.

    <uses-sdk android:minSdkVersion="4" android:targetSdkVersion="14" />  
    

    Deployed to Samsung device with Android 2.3.3
    Application has android:theme="@android:style/Theme.Light"

    Issue: application is light, but ActionBar is blue with grey icons, hardly visible against the blue background color. I also want the ActionBar to be light, so they grey icons are more visible.

    I’ve tried modifying the styles but to no avail.
    I’m probably missing something trivial.

    How do I change the background color of the ActionBar of an ActionBarActivity using XML ?

    Jonik's user avatar

    Jonik

    79.2k70 gold badges260 silver badges369 bronze badges

    asked Nov 6, 2011 at 1:53

    user77115's user avatar

    3

    As per documentation — «You can control the behaviors and visibility of the action bar with the ActionBar APIs, which were added in Android 3.0 (API level 11).»

    So, ActionBar will not work for your target environment which is at API level 10 (Android 2.3.3).

    Just in case, if you target for minimum API level 11 , you can change ActionBar’s background color by defining custom style, as:

    <resources>
        <style name="MyTheme" parent="@android:style/Theme.Holo.Light">
            <item name="android:actionBarStyle">@style/MyActionBar</item>
        </style>
    
        <style name="MyActionBar" parent="@android:style/Widget.Holo.Light.ActionBar">
            <item name="android:background">ANY_HEX_COLOR_CODE</item>
        </style>
    </resources>
    

    And, set «MyTheme» as theme for application / activity.

    Papershine's user avatar

    Papershine

    4,8502 gold badges25 silver badges45 bronze badges

    answered Feb 12, 2012 at 14:51

    lupchiazoem's user avatar

    lupchiazoemlupchiazoem

    8,0065 gold badges36 silver badges41 bronze badges

    11

    Try this

    ActionBar bar = getActionBar();
    bar.setBackgroundDrawable(new ColorDrawable("COLOR"));
    

    EdChum's user avatar

    EdChum

    364k195 gold badges795 silver badges555 bronze badges

    answered Nov 6, 2011 at 2:18

    coder_For_Life22's user avatar

    coder_For_Life22coder_For_Life22

    26.5k20 gold badges84 silver badges118 bronze badges

    9

    try this:

    ActionBar bar = getActionBar();
    bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#0000ff")));
    

    Bruno Bieri's user avatar

    Bruno Bieri

    9,55311 gold badges61 silver badges89 bronze badges

    answered Jun 23, 2013 at 14:40

    user2428604's user avatar

    user2428604user2428604

    1,2871 gold badge8 silver badges2 bronze badges

    4

    Use this — http://jgilfelt.github.io/android-actionbarstylegenerator/

    Its an amazing tool that lets you customize your actionbar with a live preview.

    I tried the earlier answers but always had problems with changing other colors like the tabs and letters and spent hours tweaking stuff. This tool helped me get my design done in just a couple of minutes.

    Here's a screenshot of the tool

    All the best! :)

    answered Jan 28, 2014 at 23:22

    Mohammad Shabaz Moosa's user avatar

    3

    I had the same problem, where my Action Bar would turn grey when I entered that code. Chances are your original style sheet looked like this:

    <style name="AppBaseTheme" parent="android:Theme.Holo.Light.DarkActionBar">
        <!-- API 14 theme customizations can go here. -->
    </style>
    

    The «DarkActionBar» was what was keeping your Action Bar grey. I changed it to this, and it worked:

    <style name="AppBaseTheme" parent="android:Theme.Holo.Light">
        <!-- API 14 theme customizations can go here. -->
        <item name="android:actionBarStyle">@style/MyActionBar</item>
    </style>
    
    <style name="MyActionBar" parent="@android:style/Widget.Holo.Light.ActionBar">
        <item name="android:background">#2aa4cd</item>
        <item name="android:titleTextStyle">@style/Theme.MyAppTheme.ActionBar.TitleTextStyle</item>
    </style>        
    
    <style name="Theme.MyAppTheme.ActionBar.TitleTextStyle" parent="android:style/TextAppearance.Holo.Widget.ActionBar.Title">
        <item name="android:textColor">#FFFFFF</item>
    </style>    
    

    I also threw in how to edit the text color. Also, no need to change anything surrounding the resources.

    -Warren

    Jared Rummler's user avatar

    Jared Rummler

    37.5k19 gold badges134 silver badges147 bronze badges

    answered May 13, 2013 at 0:43

    Warren's user avatar

    WarrenWarren

    6716 silver badges3 bronze badges

    0

    Behavior of Actionbar can also be changed in APIs < 11

    See the Android Official Documentation for reference

    I am building an app with minSdkVersion = "9" and targetSdkVersion = "21" I changed the color of action bar and it works fine with API level 9

    Here is an xml

    res/values/themes.xml

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <!-- the theme applied to the application or activity -->
        <style name="CustomActionBarTheme"
               parent="@style/Theme.AppCompat.Light.DarkActionBar">
            <item name="android:actionBarStyle">@style/MyActionBar</item>
    
            <!-- Support library compatibility -->
            <item name="actionBarStyle">@style/MyActionBar</item>
        </style>
    
        <!-- ActionBar styles -->
        <style name="MyActionBar"
               parent="@style/Widget.AppCompat.Light.ActionBar.Solid.Inverse">
            <item name="android:background">@color/actionbar_background</item>
    
            <!-- Support library compatibility -->
            <item name="background">@color/actionbar_background</item>
        </style>
    </resources>
    

    and set the color of actionbar you want

    res/values/colors.xml

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <color name="actionbar_background">#fff</color> //write the color you want here
    </resources>
    

    Actionbar color can also be defined in .class file, the snippet is

    ActionBar bar = getActionBar();
    bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#0000ff")));
    

    but this will not work with the API < 11, so styling the actionbar in xml is only way for API < 11

    3

    Direct add this line with your color code

    getSupportActionBar().setBackgroundDrawable(
        new ColorDrawable(Color.parseColor("#5e9c00")));
    

    not need to create ActionBar object every time…

    answered Jun 8, 2016 at 11:29

    CrazyMind's user avatar

    CrazyMindCrazyMind

    9461 gold badge18 silver badges21 bronze badges

    1

    On the Nexus 4 people this seems to make the color go grey.

    ActionBar bar = getActionBar(); // or MainActivity.getInstance().getActionBar()
    bar.setBackgroundDrawable(new ColorDrawable(0xff00DDED));
    bar.setDisplayShowTitleEnabled(false);  // required to force redraw, without, gray color
    bar.setDisplayShowTitleEnabled(true);
    

    (all credit to this post, but it is buried in the comments, so I wanted to surface it here)
    https://stackoverflow.com/a/17198657/1022454

    Community's user avatar

    answered May 19, 2014 at 3:43

    John Ballinger's user avatar

    John BallingerJohn Ballinger

    7,3225 gold badges40 silver badges51 bronze badges

    1

    try one line code :

    getActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.MainColor)));
    

    answered Feb 4, 2015 at 10:54

    SANAT's user avatar

    SANATSANAT

    8,27655 silver badges65 bronze badges

    3

    Use below code to provide different color to actionbar text and actionbar background just use below theme in manifest against the activity in which you want output :)

    <style name="MyTheme" parent="@android:style/Theme.Holo.Light">
        <item name="android:actionBarStyle">@style/MyActionBar</item>
    </style>
    
    <style name="MyActionBar" parent="@android:style/Widget.Holo.Light.ActionBar">
        <item name="android:titleTextStyle">@style/TitleBarTextColor</item>
        <item name="android:background">YOUR_COLOR_CODE</item>
    </style>
    
    <style name="TitleBarTextColor" parent="@style/TextAppearance.AppCompat.Widget.ActionBar.Title">
        <item name="android:textColor">YOUR_COLOR_CODE</item>
    </style>
    

    Jared Rummler's user avatar

    Jared Rummler

    37.5k19 gold badges134 silver badges147 bronze badges

    answered Aug 21, 2014 at 8:44

    Android is everything for me's user avatar

    2021: Kotlin oneliner with no deprecation:

    supportActionBar?.setBackgroundDrawable(ColorDrawable(ContextCompat.getColor(this,R.color.red)))
    

    Simply put it into onCreate and change the color depending on your needs

    answered Apr 15, 2021 at 16:27

    Merthan Erdem's user avatar

    Merthan ErdemMerthan Erdem

    5,2702 gold badges21 silver badges27 bronze badges

    This is how you can change the color of Action Bar.

    import android.app.Activity;
    import android.content.Context;
    import android.graphics.Color;
    import android.graphics.drawable.ColorDrawable;
    import android.os.Build;
    import android.support.v4.content.ContextCompat;
    import android.support.v7.app.ActionBar;
    import android.support.v7.app.AppCompatActivity;
    
    
    public class ActivityUtils {
    
    public static void setActionBarColor(AppCompatActivity appCompatActivity, int colorId){
        ActionBar actionBar = appCompatActivity.getSupportActionBar();
        ColorDrawable colorDrawable = new ColorDrawable(getColor(appCompatActivity, colorId));
        actionBar.setBackgroundDrawable(colorDrawable);
    }
    
    public static final int getColor(Context context, int id) {
        final int version = Build.VERSION.SDK_INT;
        if (version >= 23) {
            return ContextCompat.getColor(context, id);
        } else {
            return context.getResources().getColor(id);
        }
    }
    }
    

    From your MainActivity.java change the action bar color like this

        ActivityUtils.setActionBarColor(this, R.color.green_00c1c1);
    

    answered May 25, 2017 at 9:00

    Siddarth Kanted's user avatar

    Siddarth KantedSiddarth Kanted

    5,6481 gold badge29 silver badges20 bronze badges

    0

    When you are Extending Activity use following Code

    ActionBar actionbar = getActionBar();
    actionbar.setBackgroundDrawable(new ColorDrawable("color"));
    

    When you are Extending AppCompatActivity use following Code

    ActionBar actionbar = getSupportActionBar();
    actionbar.setBackgroundDrawable(new ColorDrawable("color"));
    

    Joshua Pinter's user avatar

    Joshua Pinter

    43.9k23 gold badges239 silver badges243 bronze badges

    answered Mar 14, 2018 at 6:00

    arlo shie's user avatar

    arlo shiearlo shie

    1341 silver badge8 bronze badges

    Sometimes this option throws NullPointerException

    ActionBar actionbar = getActionBar();
    actionbar.setBackgroundDrawable(new ColorDrawable("color"));

    But this option is worked for me. So you can try this.

    getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#FFFFFF")));
    

    Happy Coding

    answered Feb 4, 2020 at 3:54

    Shahadat Hossain's user avatar

    This worked for me, for AppCompatActivity,

        <item name="actionBarStyle">@style/BlackActionBar</item>
    </style>
    
    <style name="BlackActionBar" parent="@style/Widget.AppCompat.ActionBar.Solid">
        <item name="background">@android:color/black</item>
        <item name="titleTextStyle">@style/BlackActionBarTitleTextStyle</item>
    </style>
    
    <style name="BlackActionBarTitleTextStyle" parent="@style/TextAppearance.AppCompat.Widget.ActionBar.Title">
        <item name="android:textColor">@android:color/white</item>
        <item name="android:fontFamily">@font/cinzel_decorative</item>
    </style>
    

    answered Feb 28, 2019 at 18:07

    Tejasvi Hegde's user avatar

    If you are using androidx AppCompact. Use below code.

    androidx.appcompat.app.ActionBar actionBar = getSupportActionBar();
    actionBar.setBackgroundDrawable(new ColorDrawable("Color"));
    

    answered Feb 15, 2020 at 10:56

    Dinith Rukshan Kumara's user avatar

    0

    This code may be helpful

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light">
        <!-- Customize your theme here. -->
    </style>
    <style name="Theme.MyTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- customize the color palette -->
        <item name="colorPrimary">@color/material_blue_500</item>
        <item name="colorPrimaryDark">@color/material_blue_700</item>
        <item name="colorAccent">@color/material_blue_500</item>
        <item name="colorControlNormal">@color/black</item>
    
    </style>
    <style name="CardViewStyle" parent="CardView.Light">
        <item name="android:state_pressed">@color/material_blue_700</item>
        <item name="android:state_focused">@color/material_blue_700</item>
        <!--<item name="android:background">?android:attr/selectableItemBackground</item>-->
    </style>
    

    Jared Rummler's user avatar

    Jared Rummler

    37.5k19 gold badges134 silver badges147 bronze badges

    answered Feb 26, 2015 at 11:49

    Qutbuddin Bohra's user avatar

    Qutbuddin BohraQutbuddin Bohra

    1,1751 gold badge11 silver badges29 bronze badges

    Its very simple for those who are using API 21 or greater Use this code below

    for Dark ActionBar

    <resources>
    <style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="android:background">@color/colorDarkGrey</item>
    </style>
    

    for_LightActionBar

    <resources>
    <style name="AppTheme" parent="Theme.AppCompat.Light.ActionBar">
        <item name="android:background">@color/colorDarkGrey</item>
    </style>
    

    Community's user avatar

    answered Dec 22, 2019 at 8:54

    nirazverma's user avatar

    nirazvermanirazverma

    9117 silver badges14 bronze badges

    Use This code ..to change action bar background color.
    open «res/values/themes.xml» (if not present, create it)
    and add

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
    <!-- the theme applied to the application or activity -->
    <style name="CustomActionBarTheme"
           parent="@android:style/Theme.Holo.Light.DarkActionBar">
        <item name="android:actionBarStyle">@style/MyActionBar</item>
    </style>
     <!-- ActionBar styles -->
    <style name="MyActionBar"
           parent="@android:style/Widget.Holo.Light.ActionBar.Solid.Inverse">
        <item name="android:background">@drawable/actionbar_background</item>
    </style>
    

    Note : this code works for android 3.0 and higher versions only

    answered Sep 29, 2015 at 14:01

    Amey Bawiskar's user avatar

    Amey BawiskarAmey Bawiskar

    3611 gold badge3 silver badges17 bronze badges

    Use this, it would work.

    ActionBar actionbar = getActionBar();
    actionbar.setBackgroundDrawable(new ColorDrawable("color"));
    

    answered Aug 24, 2016 at 5:19

    Pankaj Lilan's user avatar

    Pankaj LilanPankaj Lilan

    4,0561 gold badge29 silver badges48 bronze badges

    getActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.TabColor)));
    

    color.xml file:

    <resources> <color name="TabColor">#11FF00</color> </resources>`
    

    Nathaniel Ford's user avatar

    answered Dec 30, 2015 at 18:32

    Chandresh Kachariya's user avatar

    Понравилась статья? Поделить с друзьями:

    Читайте также:

  • Как изменить цвет 1с предприятие
  • Как изменить хэш файла
  • Как изменить хук woocommerce
  • Как изменить худое лицо
  • Как изменить худ стима

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии