在自定义对话框中设置TextView的文本

7

我想在自定义对话框中的TextView中以编程方式设置文本,以便我可以使用Html.fromHtml。我应该在哪个函数中调用setText?我已经尝试在onCreateDialog中进行操作,但这实际上并没有更改文本。

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个回答

17

试试这个:

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

谢谢!所以我猜问题在于Activity.findViewById()只会在传递给活动的setContentView()方法的布局中查找,而在我的情况下,它并没有包括对话框使用的视图。 - Max Radin
2
有点晚了,但你也可以使用 TextView tv = myDialog.findViewById(R.id.myDialogsTextView) - Smitty-Werben-Jager-Manjenson
@Smitty-Werben-Jager-Manjenson,我回复有点晚,但是我觉得你的答案对我更加直观,我会用在我的类似问题上。谢谢! - Bosco Tsin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接