11

As we know, a colored background of action bar permitted in sdk level 11, watch this. But there are some applications with colored action bar that have min sdk lower than 11. For example Whatsapp has green action bar but has min sdk:7 WhatsApp FAQ, or the Telegram application has min sdk:8 Telegram FAQ, but has blue action bar.

How these applications work? And how I can do this?

android.app.ActionBar actionBar = (android.app.ActionBar) getActionBar();
actionBar.setDisplayShowHomeEnabled(false);
View mActionBarView = getLayoutInflater().inflate(R.layout.action_bar_main, null);
actionBar.setCustomView(mActionBarView);
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);

This code requires minSdk = 11, for getActionBar(). Please help me.

2 Answers2

6

the Toolbar (new name for the ActionBar introduced in Lollipop) is just a normal View.

Link: https://developer.android.com/reference/android/support/v7/widget/Toolbar.html

you just set it's background like any other view.

// java
toolbar.setBackgroundColor(int color);
// or 
toolbar.setBackgroundResource(int resId);

// or XML
android:background="@drawable/toolbarBackground"
Budius
  • 39,391
  • 16
  • 102
  • 144
  • Link you provided for reference does not list `setBackgroundColor()` or `setBackgroundResource()` methods, or am I missing something? – Talha Aug 11 '16 at 06:04
  • @Talha apparently yes you're missing an important detail; official documentation link I provided shows that 'Toolbar' extends from 'View'. The setBackground methods are from the view class – Budius Aug 11 '16 at 08:28
  • I am not convinced by this. When I want to set a custom ActionBar with a xml layout, I should use getActionBar();. This us required in API 11. – Seyyed Mahmood Ahmadi Aug 19 '16 at 11:55
  • If you really want want to use `getActionBar()` you first should call `set`. But that on the `AppCompatActivity is called `setSupportActionBar(Toolbar);` and `getSupportActionBar();`. But noticed that the `get` method will simply return the same object u passed before. That will be the `Toolbar`. Doc: https://developer.android.com/reference/android/support/v7/app/AppCompatActivity.html#setSupportActionBar(android.support.v7.widget.Toolbar) – Budius Aug 19 '16 at 13:27
  • But please noticed that calls to `setSupportActionBar` and getSupportActionbar` are optional. You can do the same actions by simply directly accessing the `Toolbar` view, that you can just declared on your XML layout and use a `.NoActionBar` style. – Budius Aug 19 '16 at 13:29
0

To change colour of your toolbar use this:

getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.toolbar_color_primary)));
swetabh suman
  • 1,949
  • 2
  • 19
  • 24