更改操作栏颜色时崩溃

Crash on changing action bar color

我正在添加

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

到我的主要 activity onCreate。一旦应用程序开始执行,它就会停止响应。我做错了什么?

我的 AndroiManifest

<application android:theme="@style/AppTheme" >

我的风格

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

使用 minSdkVersion 21.

假设您使用 ActionBarActivity (as that what corresponds with the AppCompat theme), you should always use getSupportActionBar() 而不是 getActionBar() - 从修订版 21 开始,getActionBar() 将始终 return null for ActionBarActivity .

getSupportActionBar() -- android.support.v7.app.ActionBarActivity return android.support.v7.app.ActionBar

getActionBar() -- android.app.Activity returnandroid.app.ActionBar

ActionBar bar = getSupportActionBar();
    ColorDrawable colorDrawable = new  ColorDrawable(Color.parseColor(colorCode));
    bar.setBackgroundDrawable(colorDrawable);

更多详情可以访问here