Set text in TextView in custom dialog

2019-07-13 12:58发布

问题:

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

回答1:

Try this:

View content =  inflater.inflate(R.layout.infodialog, null);   
builder.setView(content);
TextView textView = (TextView) content.findViewById(R.id.info);