0

我只是想在一个非常简单的应用程序中使用android.support.v7.widget.Toolbar 。Activity文件包含:

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

}

主要布局文件有:

<?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>

并且toolbar_main.xml有:

<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" />

上面给出的代码一切正常。但是对于include标签,如果我使用与工具栏 id(ietoolbar)不同的 id(假设 'toolbar_newname'),那么我会在 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)

那么为什么会发生错误呢?为什么我必须保持两个 id 相同?

4

0 回答 0