如何在 Fragment Dialog 中设置标题和文本?

How to set the title and text in FragmentDialog?

我有一个包含 5 个片段的 MainActivity,其中 2 个在右上角的工具栏上有一个帮助图标。我在其他 3 个片段上隐藏了这个图标。单击帮助图标后,会出现一个带有标题、消息和肯定按钮的警告对话框。

这是我的警报对话框代码:

public class HelpDialogFragment extends DialogFragment {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("Help");
        builder.setMessage("Placeholder");
        builder.setPositiveButton("Got It", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {}
            });
        return builder.create();
    }
}

这就是我在 MainActivity 中展示它的方式:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.action_help:
            DialogFragment helpDialog = new HelpDialogFragment();
            helpDialog.show(getSupportFragmentManager(), "dialogHelp");
            return true;
    }
    return super.onOptionsItemSelected(item);
}

以上代码有效,但我想根据所选片段显示不同的消息,那么如何更改消息?我试过这个来改变标题

helpDialog.getDialog().setTitle("Some Text");

请注意,我想更改对话框消息,即主要内容,我在 getDialog() 上只有 setTitle() 方法,而在 setMessage() 上没有,上面的 setTitle 只是例如目的,但即使它抛出 NullPointerException。

在上面的截图中可以看到,"Placeholder"文本是我在创建AlertDialog时添加的默认文本,但现在如何更改它?

通过阅读您的 post 和评论,您似乎需要根据可见的片段设置不同的标题。对话框的创建是从 Activity 开始的,因此您不确定要设置什么标题。

问题本质上是识别可见片段并根据它设置消息。

您可以像这样传递带有参数的消息。

Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putString(message, "My title");
fragment.setArguments(bundle);  

然后在您的 Fragment 中获取数据(例如在 onCreate() 方法中)

Bundle bundle = this.getArguments();
if (bundle != null) {
        String message = bundle.getString(message, defaultValue);
}

如何识别当前可见片段?您可以按照 these 答案中的建议执行此操作。获取到当前片段后,根据它在上面的参数中发送消息即可。

通过结合以上 2 个想法,您可以做到这一点。

另一种方法是从片段而不是 Activity 开始对话,但这会涉及更多更改,因此上述方法更好。

首先在调用 HelpDialogFragment 时通过包传递所需的消息 class

HelpDialogFragment helpDialog = new HelpDialogFragment();

Bundle bundle = new Bundle();
bundle.putString("placeholder", "Custom placeholder");
helpDialog.setArguments(bundle);
helpDialog.show(getSupportFragmentManager(), "dialogHelp");

现在修改您的 HelpDialogFragment class 像这样创建对话框

public class HelpDialogFragment extends DialogFragment {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("Help");
        if (getArguments() != null) 
            builder.setMessage(getArguments().getString("placeholder",""));
        builder.setPositiveButton("Got It", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {}
            });
        return builder.create();
    }
}