5

我在获取数据时遇到问题,用户输入dialog(使用自定义布局)。看代码:

单位.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">

<EditText
    android:id="@+id/editText1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
</EditText>
</RelativeLayout>

代码:

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    LayoutInflater inflater = this.getLayoutInflater();
    builder.setView(inflater.inflate(R.layout.unit, null)); 
    AlertDialog dialog = builder.create();
    dialog.show();

Dialog以我创建的布局打开,但是

    builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
          @Override
          public void onClick(DialogInterface dialog, int which) {
                        EditText text = (EditText)findViewById(R.id.editText1);
                        Toast.makeText(getApplicationContext(), text.getText(), Toast.LENGTH_SHORT).show();
            dialog.dismiss();
          }

        });

产生运行时错误:java.lang.NullPointerException。哪里有问题?

4

2 回答 2

4

用这个..

 builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
      @Override
      public void onClick(DialogInterface dialog, int which) {
                    EditText text = (EditText) dialog.findViewById(R.id.editText1);
                    Toast.makeText(getApplicationContext(), text.getText(), Toast.LENGTH_SHORT).show();
        dialog.dismiss();
      }

    });
于 2012-12-31T18:47:58.860 回答
1

找到了:

AlertDialog aDialog = (AlertDialog) dialog;
EditText name = (EditText) aDialog.findViewById(R.id.editText1);
于 2012-12-31T14:43:44.733 回答