我目前正在尝试向操作栏添加自定义布局,但不断遇到空指针异常,并且无法找到解决方法。
这是我的 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 并运行最低 API 7。
提前致谢。
最佳答案
将 getActionBar()
替换为 getSupportActionBar()
并更改您的导入以匹配。
关于java - 尝试访问 ActionBar 时出现空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31212010/