java - 空对象引用工具栏android

标签 java android object nullpointerexception

<分区>

我正在尝试制作第二个工具栏,紧挨着我顶部栏中的工具栏。 基本上有一个 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();

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>

错误:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.Toolbar.setTitle(java.lang.CharSequence)' 在空对象引用上

最佳答案

使用

 View v = getLayoutInflater().inflate(R.layout.popupscherm,null);
 toolbar = (Toolbar) v.findViewById(R.id.toolbar);

代替

toolbar = (Toolbar) findViewById(R.id.toolbar);

因为 view vpopupscher.xml View ,否则用这个 findViewById(R.id.toolbar); 你试图找到当前设置的 Activity 布局中的工具栏与 popupscherm.xml

不同

关于java - 空对象引用工具栏android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40022793/

相关文章:

python - 调用 Python 静态方法对象

Java使用正则表达式分割并丢弃重复的字符

java - 对象初始化 - 构造函数与类类型和方法访问的关系

java - 在抽象 Java 类中使用泛型类型声明

java - 通过 hibernate 仅更新选定的字段,而不更新数据库中的所有列

android - 如何在 Eclipse for Android 的 logcat 中隐藏、删除、过滤日志

java - 仅显示 ListView 中的第一项

android - 在代码里面打开GPS

javascript - 在对象内插入按钮?

javascript - 获取 Javascript 文件中所有对象的数组