I have a custom dialog and when I try to get the value of an EditText it returns null.
This line returns null
EditText et = (EditText)findViewById(R.id.username_edit);
Here is the code in its entirety.
protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_TEXT_ENTRY: LayoutInflater factory = LayoutInflater.from(this); final View textEntryView = factory.inflate(R.layout.alert_dialog_text_entry, null); return new AlertDialog.Builder(TicTacToe.this) //.setIconAttribute(android.R.attr.alertDialogIcon) .setTitle(getTitleText()) .setView(textEntryView) .setPositiveButton("JOIN GAME", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { try { EditText et = (EditText)findViewById(R.id.username_edit); playerName = et.getText().toString(); } catch (Exception e) { } } }) .create(); } return null; }
findViewById returns an instance of View , which is then cast to the target class. All good so far. To setup the view, findViewById constructs an AttributeSet from the parameters in the associated XML declaration which it passes to the constructor of View . We then cast the View instance to Button .
FindViewById<T>(Int32)Finds a view that was identified by the id attribute from the XML layout resource.
In the case of an Activity , findViewById starts the search from the content view (set with setContentView ) of the activity which is the view hierarchy inflated from the layout resource. So the View inflated from R. layout. toast is set as child of content view?
findViewById is the method that finds the View by the ID it is given. So findViewById(R. id. myName) finds the View with name 'myName'.
In my case: First I must call the
dialog.show(),
and only after it I was able to use
dialog.findviewById(R.id.myID).
If I missed to call the show(), than I got a null back with findViewByID.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With