Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call findViewById on an AlertDialog.Builder?

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
like image 233
Lv99Zubat Avatar asked Mar 04 '16 23:03

Lv99Zubat


2 Answers

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);
like image 71
RominaV Avatar answered Nov 04 '22 01:11

RominaV


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.

like image 45
curious_george Avatar answered Nov 04 '22 01:11

curious_george