Lv99Zubat
Lv99Zubat

Reputation: 853

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

Upvotes: 17

Views: 16473

Answers (2)

curious_george
curious_george

Reputation: 642

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.

Upvotes: 6

RominaV
RominaV

Reputation: 3415

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);

Upvotes: 29

Related Questions