setBackgroundDrawable在创建Android Custom ActionBar时抛出NullPointerException

时间:2014-12-18 18:47:23

标签: android exception android-actionbar

我在创建Custom ActionBar时在setBackgroundDrawable上得到NullPointerException。         protected void onCreate(Bundle savedInstanceState){         super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
    ActionBar actionBar = getActionBar();
    Bitmap b = BitmapFactory.decodeResource(getResources(),
            R.drawable.ic_launcher);

    actionBar.setBackgroundDrawable(new BitmapDrawable(getResources(), b));
    actionBar.setCustomView(R.layout.actionbar_view);

LogCat结果如下:

Caused by: java.lang.NullPointerException
        at actionbarcustomview.practice.nkd.actionbarcustomviews.MainActivity.onCreate(MainActivity.java:30)
        at android.app.Activity.performCreate(Activity.java:4465)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1931)

第30行

actionBar.setBackgroundDrawable(new BitmapDrawable(getResources(), b));

我正在使用Android Studio,配置是

    defaultConfig {
    applicationId "actionbarcustomview.practice.nkd.actionbarcustomviews"
    minSdkVersion 17
    targetSdkVersion 21
    versionCode 1
    versionName "1.0"
}

请帮我解决这个问题。

1 个答案:

答案 0 :(得分:0)

以下是一篇应该有所帮助的博文:

http://blog.perpetumdesign.com/2011/08/strange-case-of-dr-action-and-mr-bar.html

问题是ActionBar actionBar = getActionBar();会返回null