setOnClickListener返回空异常

时间:2019-04-12 16:14:17

标签: android

在我的android应用中,我有一个页面,其中包含带有标题和子项的可扩展列表。我想要做的是单击子项之一,并显示一个新对话框。现在,我在点击监听器上收到了一个null异常,但我觉得我已正确设置了所有内容。这是代码:

        dialog = new Dialog(this);
        dialog.setContentView(curriculum_description);
        dialog.setTitle("Description");

        curriculumExpandable = findViewById(R.id.expandedListItem);
        curriculumExpandable.setOnClickListener(v -> dialog.show());

这是我正在调用的xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">

    <TextView
        android:id="@+id/curriculumInfo"
        android:layout_width="50dp"
        android:layout_height="20dp"
        android:clickable="true"
        android:focusable="true" />


</RelativeLayout>

curriculumExpandable是TextView,expandedListItem是扩展列表(也是TextView)中子项的ID。单击该子项后,应转到显示的xml。

1 个答案:

答案 0 :(得分:0)

不清楚您在何处声明了视图。 如果在调用onClickListener时尚未创建视图,则可能会得到null异常。

例如,在片段的OnCreateView中设置onClickListener可能会导致空异常。

您可能还想考虑在视图不存在的情况下添加空检查的另一件事 在您设置监听器时创建的,就像这样:

curriculumExpandable?.setOnClickListener(v -> dialog.show());
相关问题