从OnClickListener中的EditText调用getText时发生空指针异常

时间:2012-05-21 13:08:28

标签: android android-widget

我有一个自定义对话框。当我单击“确定”时,我希望它从其EditText字段中获取文本。但是,它会抛出空指针异常。

代码:

AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.dialog_delivered, (ViewGroup)findViewById(R.id.llDeliveredDialog));

builder.setMessage("Dialog message");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
    final EditText text = (EditText)findViewById(R.id.etGivenTo);
    String value = text.getText().toString();
    }
});

builder.setCancelable(false);
builder.setView(layout);
builder.show();

XML布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/llDeliveredDialog"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/etGivenTo"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:ems="10" >

        <requestFocus />
    </EditText>

</LinearLayout>

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:7)

 final EditText text = (EditText)layout.findViewById(R.id.etGivenTo);
                                 ^^^^^^

答案 1 :(得分:1)

builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
    final EditText text = (EditText)layout.findViewById(R.id.etGivenTo); 
    String value = text.getText().toString();
    }
});