尝试访问ActionBar时出现空指针异常

时间:2015-07-03 17:43:32

标签: java android

我目前正在尝试将自定义布局添加到我的操作栏,但仍然遇到空指针异常并且无法找到解决方法。

这是我的onCreateOptionsMenu

    @Override
public boolean onCreateOptionsMenu(Menu menu)
{
    ActionBar mActionBar = getActionBar();
    LayoutInflater mInflater = LayoutInflater.from(this);

    View mCustomView = mInflater.inflate(R.layout.custom_actionbar, null);
    TextView mTitleTextView = (TextView) mCustomView.findViewById(R.id.menuText);
    mTitleTextView.setText("Insert Title Here");

    ImageButton imageButton = (ImageButton) mCustomView.findViewById(R.id.menuPlusButton);
    imageButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(getApplicationContext(), "Start New Course", Toast.LENGTH_LONG).show();
        }
    });

    mActionBar.setDisplayShowHomeEnabled(false);
    mActionBar.setDisplayShowTitleEnabled(false);
    mActionBar.setCustomView(mCustomView);
    mActionBar.setDisplayShowCustomEnabled(true);
    return super.onCreateOptionsMenu(menu);
}

错误似乎发生在mActionBar.setDisplayShowHomeEnabled(false),表明ActionBar mActionBar = getActionBar()返回null,我无法弄清楚原因。我扩展AppCompatActivity并运行min API 7.

提前致谢。

1 个答案:

答案 0 :(得分:4)

getActionBar()替换为getSupportActionBar()并更改您的导入以匹配。

相关问题