17

I'm trying to get a reference to a TextView in the AlertDialog with this code:

AlertDialog.Builder logoutBuilder = new AlertDialog.Builder(getActivity());      
TextView alertTextView = (TextView) logoutBuilder.findViewById(android.R.id.message);
alertTextView.setTextSize(40);

But I'm getting a compiler error at findViewById:

Cannot cast from AlertDialog.Builder to Dialog
The method findViewById(int) is undefined for the type AlertDialog.Builder
RominaV
  • 3,335
  • 1
  • 29
  • 59
Lv99Zubat
  • 853
  • 2
  • 10
  • 27
  • Possible duplicate of [findViewById from AlertDialog (with Custom Layout) - NullPointerException](http://stackoverflow.com/questions/24498182/findviewbyid-from-alertdialog-with-custom-layout-nullpointerexception) – M. Reza Nasirloo Mar 05 '16 at 00:02

2 Answers2

28

Create the dialog from the AlertDialog.Builder, like so:

AlertDialog alert = builder.create();

Then, from the alert, you can invoke findViewById:

TextView alertTextView = (TextView) alert.findViewById(android.R.id.message);
alertTextView.setTextSize(40);
RominaV
  • 3,335
  • 1
  • 29
  • 59
  • 1
    i can't access the textview's if i do that. they come up as null. – Lv99Zubat Mar 08 '16 at 00:04
  • 17
    nvm, i need to search for the textview AFTER .show() is called. Then it worked. Thanks as this answer led me to that. – Lv99Zubat Mar 08 '16 at 00:37
  • `View v = inflater.inflate(R.layout.activity_main, null);` generates a warning. Using `View.inflate(..., null, false)` just hides the warning but doesn't solve the problem. The correct method is to use `builder.setView(R.layout.edit_account_dialog); dialog = builder.create();` but `findViewById` will be usable only after the activity has called `dialog.show()` ; it rises another problem: the dialog's `findViewById` aren't useable before `show()` and aren't callable easily after `show()`. Btw calling the `findViewById` in the activity just after `dialog.show()` isn't a good practice. – JarsOfJam-Scheduler Mar 15 '19 at 22:16
5

The currently accepted answer does not work for me: it gives me a null TextView object. Instead, I needed to call findViewById from the View that I inflated.

AlertDialog.Builder builder = new AlertDialog.Builder(MyActivity.this);
View v = getLayoutInflater().inflate(R.layout.view_dialog, null);
builder.setView(v);

Now, I can find the TextView by using v's findViewById:

TextView card_info = v.findViewById(R.id.view_card_info_card_num);

Later, I call builder.show() to display the AlertDialog.

I found it odd that the accepted answer did not work for me. It appears consistent with the documentation. Nevertheless, I had to approach it this way.

curious_george
  • 622
  • 2
  • 8
  • 19
  • I think it did not work for because you use a custom dialog layout rather than using the default layout. He tried to get a textview using **android.R.id.message** which means the original dialog layout – DemoDemo Feb 13 '20 at 20:55