Trouble implementing Material Theme

时间秒杀一切 提交于 2019-11-30 17:07:40

UPDATE: your actual problem is that you have the <android.support.v7.widget.Toolbar code in an own toolbar.xml file. this has to be in activity_main.xml and all other layouts that you want to use with an actionbar.


The Toolbar allows more customization than the default ActionBar (mostly appearance related). If you want or need to customize the actionbar, you need to set a Toolbar as ActionBar. If not. you dont need to do that and you can simply use the default ActionBar provided by the Theme (you have to remove the windowActionBar false part from your theme).

if you want to use a toolbar, you have to ensure that there is a Toolbar view in your layouts.

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimaryDark"/>

then you can use your code.

but you should also ensure that getSupportActionBar() does not return null before you use it. in case that the layout is missing the toolbar.


OLD ANSWER BELOW


Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
    setSupportActionBar(toolbar);
}
getSupportActionBar().setDisplayHomeAsUpEnabled(true); // NULL POINTER EXCEPTION here
getSupportActionBar().setHomeButtonEnabled(true);

you only set the toolbar if the view has been found. it seems that the view has not been found.

after the if you access the actionbar that has not been set and is therefore null.

also in your them you have <item name="windowActionBar">false</item> that disables the default actionbar.

you can do following:

  • set windowActionbar to true in your theme then you have the default actionbar and you wont need the Toolbar.
  • if you want to use your toolbar on a non default location you have to ensure that findViewById(R.id.toolbar) actually returns a toolbar (check your layouts that there is a Toolbar with that id)
  • or do not use getSupportActionBar without testing it for null.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!