Article Directory
1. Exception handling
Attempt to invoke virtual method ‘ActionBar.setHomeButtonEnabled(boolean)’ on a null object reference
java.lang.RuntimeException: Unable to start activity ComponentInfo{
}: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.setHomeButtonEnabled(boolean)' on a null object reference
// ......
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.setHomeButtonEnabled(boolean)' on a null object reference
// ......
2. The reason
The ToolBar layout file is not referenced in the Activity layout, but only dynamically set, so that when you use or get the ActionBar, you will get an error because the ToolBar is not set successfully.
3. Solve
3.1 Layout file
// 主布局文件
<LinearLayout android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<include layout="@layout/toobar"/>
</LinearLayout>
// toolbar.xml文件
<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toolbar_test"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:contentInsetStart="0dp">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="Toolbar"
android:textSize="20dp" />
</androidx.appcompat.widget.Toolbar>
3.2 Java files
private void initToolBar() {
Toolbar toolbar_test = (Toolbar)findViewById(R.id.toolbar_test);
setSupportActionBar(toolbar_test);
}
4. Results
5. Matters needing attention
Java introduces ToolBar as follows:
import androidx.appcompat.widget.Toolbar;