findViewById() returns null for Views in a Dialog
Solution 1:
Calling findViewById()
will search for views within your Activity's layout and not your dialog's view. You need to call findViewById()
on the specific View
that you set as your dialog's layout.
Try this
private void initSearch() {
AlertDialog.Builder searchDialog = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
searchDialog.setTitle("Search Photos");
searchDialog.setMessage("Specify tag and value...");
// R.layout.search_dialog is my custom layour, it displays fine, it works.
View dialogView = inflater.inflate(R.layout.search_dialog, null);
searchDialog.setView(dialogView);
EditText tagText = (EdiText) dialogView.findViewById(R.id.tagField);
searchDialog.setPositiveButton( ... ) ...
AlertDialog myAlert = searchDialog.create(); //returns an AlertDialog from a Builder.
myAlert.show();
}
Notice how I'm inflating the view and storing it in a View
named dialogView
. Then, to find your EditText
named tagField
, I'm using dialogView.findViewById(R.id.tagField);
Solution 2:
The TextView
with id text123
has to be declared inside the Layout
you set with setContentView