java - 尝试访问自定义 AlertDialog 的子级会导致 NullPointerException

标签 java android dialog nullpointerexception android-custom-view

我正在 Android 中尝试自定义 AlertDialog,并偶然发现了一个我不明白的 Exception

我在 res/layout/dialog_resident_next_dates.xml 中定义了自定义 AlertDialog

<TextView 
    android:id="@+id/custom_dialog_title"
    style="@style/customdialog_title"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

<View
    android:layout_width="match_parent"
    android:layout_height="1dip"
    android:background="@color/grey3"/>

<TextView 
    android:id="@+id/custom_dialog_content"
    style="@style/customdialog_paragraph"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

在触发AlertDialog的方法中,实现了以下内容

public void onClickResidentDates(View v){
    String datesOliva = "a (...) long (...) string";

    AlertDialog.Builder alert = new AlertDialog.Builder(this);
    alert.setCustomTitle(getLayoutInflater().inflate(R.layout.dialog_resident_next_dates, null));
    alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });
    alert.show();

    TextView dialogContent = (TextView) findViewById(R.id.custom_dialog_content);
    dialogContent.setText(datesOliva);
}

更准确地说,这会导致第 364 行出现 NullPointerException

dialogContent.setText(datesOliva);

为什么会抛出这个Exception?布局正确膨胀(使用空 View 进行测试),并且 TextView 应该存在。在这个方法中,仅构建 Dialog 是否有任何问题(我认为这都不是问题,因为 .show() 应该创建 AlertDialog)?

注意:由于我不完全知道如何完全创建自定义 AlertDialog,因此我使用了一些“hack”。整个自定义布局 xml 设置为标题,而默认消息 View 设置为空。

最佳答案

使用

View v = getLayoutInflater().inflate(R.layout.dialog_resident_next_dates, null);
alert.setView(v);
TextView dialogContent = (TextView) v.findViewById(R.id.custom_dialog_content);
dialogContent.setText(datesOliva); 

findViewById 在当前扩展布局中查找具有 id 的 View 。您可以填充自定义布局,并且那里有 TextView 。所以你需要使用 View 对象来初始化你的 View 。

还有

public AlertDialog.Builder setCustomTitle(查看customTitleView)

使用自定义 View customTitleView设置标题。

所以你可能需要alert.setView(v)

public void setView( View View )

设置要在该对话框中显示的 View 。

关于java - 尝试访问自定义 AlertDialog 的子级会导致 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20575036/

相关文章:

java - 如何从数组中获取唯一元素和结果数组的长度

有规范问题的 Java Print 程序?

java - 如何解决此错误 : java. lang.NoSuchFieldError : UTF_32BE?

java - 打开 Activity 期间应用程序崩溃

java - 从 EditText 中检索文本

Android:对话框中单选组的空指针异常

java - 我想在一个对话框中显示多个输出。我该如何实现这个目标?

android - Android 上高效的批量 SQL 查询执行,用于升级数据库

Android主项目与库项目-如何在项目之间传递设置

java - 列表 Activity 和对话框