Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

findviewbyid returns null in a dialog

Tags:

java

android

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; } 
like image 816
Arizona1911 Avatar asked Apr 02 '11 19:04

Arizona1911


People also ask

What does findViewById return?

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 .

What does this method do findViewById?

FindViewById<T>(Int32)Finds a view that was identified by the id attribute from the XML layout resource.

How does findViewById work on Android?

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?

What is findViewById R ID?

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'.


1 Answers

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.

like image 59
narancs Avatar answered Oct 13 '22 23:10

narancs