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);
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, 2022Comments
-
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 callsetText
? I've tried doing it inonCreateDialog
, 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 almost 9 yearsThanks! So I guess the issue is that
Activity.findViewById()
only looks in the layout passed to the activity'ssetContentView()
method, which in my case did not include the View used by the dialog. -
Smitty-Werben-Jager-Manjenson over 4 yearsKind of late but you could also use
TextView tv = myDialog.findViewById(R.id.myDialogsTextView)