How do I call findViewById on an AlertDialog.Build

2019-04-26 15:58发布

问题:

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

回答1:

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