I am just trying to use the android.support.v7.widget.Toolbar in a very simple app. The Activity
file contains:
package com.example.istiaqueahmed.toolbarapp;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.support.v7.widget.Toolbar;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find the toolbar view and set as ActionBar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// ...
// Display icon in the toolbar
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setLogo(R.mipmap.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);
}
// Menu icons are inflated just as they were with actionbar
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
And the main layout file has:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
>
<!-- Load the toolbar here -->
<include
layout="@layout/toolbar_main"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<!-- Rest of content for the activity -->
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="This is the line "
android:layout_below="@id/toolbar"
/>
</RelativeLayout>
And toolbar_main.xml
has :
<app:android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar"
app:contentInsetLeft="0dp"
app:contentInsetStart="0dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="@style/ToolbarTheme"
app:titleTextAppearance="@style/Toolbar.TitleText"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
Everything works fine with the code given above. But for the include
tag if I use an id (suppose 'toolbar_newname') different from that of the toolbar id (i.e.toolbar), then I get the following error in logcat.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method '
void android.support.v7.app.ActionBar.
setDisplayHomeAsUpEnabled(boolean)'
on a null object reference at com.example.istiaqueahmed.toolbarapp.MainActivity.
onCreate(MainActivity.java:20)
So why does the error occur ? Why do I have to keep the two ids same ?