Android-在Android中设置自定义工具栏时发生NullPointerException

时间:2018-10-26 18:20:15

标签: java android xml

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

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

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,但无法解决问题。

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:2)

先将主题更改为NoActionBar,然后使用自定义工具栏

 <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">

答案 2 :(得分:0)

在super.onCreate(savedInstanceState)之后添加此内容

setContentView(R.layout.activity_main)