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

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

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();
    }


activity_main.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>


我查看了this,但无法解决问题。

最佳答案

您应该将setContentView(R.layout.activity_main)添加到onCreate()

07-28 08:11