首页 > 解决方案 > Android - 在 Android 中设置自定义工具栏时出现 NullPointerException

问题描述

我正在尝试将自定义图像设置到我的标题栏中。

运行以下代码将返回以下内容:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.me.project/com.me.project.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.Toolbar.setTitle(int)' on a null object reference

toolbar一片空白。为什么?R.id.app_toolbar在这里不为空。

MainActivity.java:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Toolbar toolbar = findViewById(R.id.app_toolbar);
        toolbar.setTitle(R.string.app_name);
        toolbar.setLogo(R.drawable.app_icon);
        setSupportActionBar(toolbar);

        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.container, new HomeScreenFragment());
        fragmentTransaction.commit();
    }

活动主.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/main_activity"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <include
        android:id="@+id/app_toolbar"
        layout="@layout/app_toolbar"/>

    <FrameLayout
        android:id="@+id/container"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </FrameLayout>



</android.support.constraint.ConstraintLayout>

app_toolbar.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/app_toolbar"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:minHeight="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    >

</android.support.v7.widget.Toolbar>

我看了看这个,无法解决这个问题。

标签: javaandroidxml

解决方案


你应该添加setContentView(R.layout.activity_main)onCreate()


推荐阅读