空对象参考工具栏android

aze*_*q6d 1 java android object nullpointerexception

我正在尝试紧跟Toolbar在顶部栏中的那一秒。基本上有一个Button,当按下它时,窗口中会弹出一个条。用户应该能够阅读栏上的内容并可以按Button。现在,我正在尝试在此处输入文字。但这似乎不起作用。

.java函数:(按下某个按钮时调用,显示工具栏)

public void showDialogue() {
    //Set popupscherm as view
    View v = getLayoutInflater().inflate(R.layout.popupscherm,null);
    AlertDialog.Builder adb = new AlertDialog.Builder(GraphActivity.this);
    adb.setView(v);
    // Find the toolbar view inside the activity layout
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitle("test"); //Here it gives the error
    AlertDialog alert = adb.create();

    alert.show();
Run Code Online (Sandbox Code Playgroud)

popupscherm.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:minHeight="?attr/actionBarSize"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary">
    </android.support.v7.widget.Toolbar>

    </LinearLayout>
Run Code Online (Sandbox Code Playgroud)

错误:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.Toolbar.setTitle(java.lang.CharSequence)' on a null object reference

Pav*_*ngh 5

使用

 View v = getLayoutInflater().inflate(R.layout.popupscherm,null);
 toolbar = (Toolbar) v.findViewById(R.id.toolbar);
Run Code Online (Sandbox Code Playgroud)

代替

toolbar = (Toolbar) findViewById(R.id.toolbar);
Run Code Online (Sandbox Code Playgroud)

因为view v 有其他popupscher.xml视图,findViewById(R.id.toolbar);您正在尝试在当前设置的活动布局中查找不同于以下内容的工具栏popupscherm.xml

  • 诺诺,非常感谢。我找了两个小时,这很简单。 (2认同)