Android自定义对话框

Ele*_*ec0 6 android dialog

我正在尝试按照Android开发人员网站上的教程制作自定义对话框,但每次尝试显示对话框时都会崩溃.这是我的代码:

Context mContext = getApplicationContext();
Dialog dialog = new Dialog(mContext);

dialog.setContentView(R.layout.custom_dialog);
dialog.setTitle("Custom Dialog");
dialog.show();
Run Code Online (Sandbox Code Playgroud)

这是我的布局XML:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    android:id="@+id/layout_root"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <Button
        android:id="@+id/btnConfirm"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Add text"
        android:layout_below="@+id/txtNewText"
        android:layout_alignParentLeft="true">
    </Button>
    <EditText
        android:id="@+id/txtNewText"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true">
    </EditText>
</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

JAL*_*JAL 8

考虑模式:

private static final int MY_DIALOG= 0;

protected Dialog onCreateDialog(int id) {
    Dialog dialog;
    switch(id) {
        case MY_DIALOG:
            dialog= getInstanceMyDialog();
            break;
        default:
            dialog = null;
    }
    return dialog;
}

private Dialog getInstanceMyDialog() {
    final Dialog d= new Dialog(this); //<=====THIS
    d.setContentView(R.layout.custom_dialog);
    d.setTitle("Custom Dialog");
    return d;
}
Run Code Online (Sandbox Code Playgroud)

JAL