我在获取数据时遇到问题,用户输入dialog
(使用自定义布局)。看一下代码:
unit.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
。问题在哪里?
答案 0 :(得分: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();
}
});
答案 1 :(得分:1)
找到它:
AlertDialog aDialog = (AlertDialog) dialog;
EditText name = (EditText) aDialog.findViewById(R.id.editText1);