Java android change color of actionbar

时间:2015-05-04 19:46:05

标签: java android android-actionbar

Simply want to change the color of my actionbar!

So, when I google this, it appears pretty simple...

I've seen people propose this several times:

<style name="AppTheme"
    parent="@style/Theme.AppCompat.Light.DarkActionBar">
    <item name="android:actionBarStyle">@style/MyActionBar</item>
</style>

<!-- ActionBar styles -->
<style name="MyActionBar"
    parent="@style/Widget.AppCompat.Light.ActionBar">
    <item name="android:background">#990000</item>
</style>

But I really cant get this to work. It doesn't do any thing different.. Actionbar is still black. But exactly this seems to work for other people, so I dont understand..

When I try to put this:

    ActionBar actionBar;

    actionBar = getActionBar();
    ColorDrawable colorDrawable = new ColorDrawable(Color.parseColor("#990000"));
    actionBar.setBackgroundDrawable(colorDrawable);

in my onCreate, the app just crashes...

Edit: Okay I'm an idiot for posting way too soon... Just had to put the actionBar code below the:

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

It works now, sorry for posting before I tried that...

2 个答案:

答案 0 :(得分:0)

新的Lollipop AppCompat库不使用android:命名空间进行主题化。如果您删除android:并且如下所示,则很有可能您的主题将起作用:

<style name="AppTheme"
    parent="@style/Theme.AppCompat.Light.DarkActionBar">
    <item name="actionBarStyle">@style/MyActionBar</item>
</style>

更好的方法是使用Toolbar而不是弃用ActionBar。要做到这一点,你的主题应该来自NoActionBar主题。

<style name="AppTheme"
    parent="@style/Theme.AppCompat.NoActionBar">
</style>

您必须将Toolbar添加到您自己的布局中,如下所示。这样你就可以设置你想要的任何背景。

<android.support.v7.widget.Toolbar
  android:id="@+id/toolbar_actionbar"
  android:layout_width="match_parent"
  android:layout_height="?attr/actionBarSize"
  android:background="#990000" />

答案 1 :(得分:0)

将您的主题应用于整个应用或清单上的各个活动:

<application android:theme="@style/CustomActionBarTheme" ... />