Set text in TextView in custom dialog

11,826

Try this:

View content =  inflater.inflate(R.layout.infodialog, null);   
builder.setView(content);
TextView textView = (TextView) content.findViewById(R.id.info);
Share:
11,826
Max Radin
Author by

Max Radin

Quantum software engineer at Zapata Computing with a background in first-principles and mesoscale modeling of battery materials.

Updated on June 13, 2022

Comments

  • Max Radin
    Max Radin about 2 years

    I want to set the text in a TextView contained in a custom dialog programmatically, so that I can use Html.fromHtml. In what function should I call setText? I've tried doing it in onCreateDialog, but this does not actually change the text.

    public class InfoDialogFragment extends DialogFragment {
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            // Use the Builder class for convenient dialog construction
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    
            LayoutInflater inflater = getActivity().getLayoutInflater();
    
            // Inflate and set the layout for the dialog
            // Pass null as the parent view because its going in the dialog layout
            builder.setView(inflater.inflate(R.layout.infodialog, null));
    
            TextView textView = (TextView) getActivity().findViewById(R.id.info);
            textView.setText(Html.fromHtml("<h1>Text has been correctly set</h1>"));
            ...
    
  • Max Radin
    Max Radin almost 9 years
    Thanks! So I guess the issue is that Activity.findViewById() only looks in the layout passed to the activity's setContentView() method, which in my case did not include the View used by the dialog.
  • Smitty-Werben-Jager-Manjenson
    Smitty-Werben-Jager-Manjenson over 4 years
    Kind of late but you could also use TextView tv = myDialog.findViewById(R.id.myDialogsTextView)