尝试访问自定义AlertDialog的子项会导致NullPointerException

Val*_* Ru 0 java android dialog nullpointerexception android-custom-view

我正在尝试AlertDialogAndroid中的自定义,偶然发现Exception我不明白.

AlertDialogres/layout/dialog_resident_next_dates.xml中定义了自定义

<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"/>
Run Code Online (Sandbox Code Playgroud)

在触发的方法中,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);
}
Run Code Online (Sandbox Code Playgroud)

NullPointerException更准确地导致了在线364

dialogContent.setText(datesOliva);
Run Code Online (Sandbox Code Playgroud)

为什么Exception抛出这个?布局正确充气(使用空Views 测试),TextView应该存在.有没有问题,在这个方法中,Dialog只是建立(我认为这既不是问题,因为.show()应该创建AlertDialog)?

注意:由于我不完全知道如何完全创建自定义AlertDialog,我使用了一点"黑客".整个自定义布局xml设置为标题,而默认消息View设置为空.

Rag*_*dan 5

使用

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); 
Run Code Online (Sandbox Code Playgroud)

findViewById在当前膨胀的布局中查找具有id的视图.您可以隐藏自定义布局,并在那里拥有文本视图.因此,您需要使用视图对象来初始化视图.

public AlertDialog.Builder setCustomTitle (View customTitleView)

使用自定义视图customTitleView设置标题.

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

public void setView (View view)

设置要在该对话框中显示的视图.