我有一个使用自定义布局的 AlertDialog。在 OnClick 事件中,我想读取用户输入的内容,所以我这样做:
//Login Dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
// Get the layout inflater
LayoutInflater inflater = this.getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(inflater.inflate(R.layout.dialog_signin, null))
.setPositiveButton(R.string.tvLoginTitle, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
String username = ((EditText)findViewById(R.id.loginUsername)).getText().toString();
String password = ((EditText)findViewById(R.id.loginPassword)).getText().toString();
System.out.println(username);
System.out.println(password);
ConnectionID.loginToServer(cMainActivity, username, password);
}
})
.setNegativeButton(R.string.btnExit, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
System.exit(0);
}
}).show();
但是当我想阅读里面的内容时,我总是得到一个 NullPointerException 来自 dialog_signin 的布局看起来像:
<EditText
android:id="@+id/loginUsername"
android:inputType="textEmailAddress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginBottom="4dp"
android:hint="@string/tvUsername" />
<EditText
android:id="@+id/loginPassword"
android:inputType="textPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginBottom="16dp"
android:fontFamily="sans-serif"
android:hint="@string/tvPassword"/>