如何设置DialogFragment的标题?

Ste*_*anK 162 android android-fragments android-dialogfragment

这应该是一个简单的任务,但由于某种原因,我可以找到一种方法来设置DialogFragment的标题.(我正在使用onCreateView重载设置对话框内容).

默认样式为标题留下了一个位置,但我找不到DialogFragment类的任何方法来设置它.

当该onCreateDialog方法用于设置内容时,标题以某种方式神奇地设置,所以我想知道这是否是设计,或者在使用onCreateView重载时有一个特殊的技巧来设置它.

Rob*_*mes 310

您可以使用 getDialog().setTitle("My Dialog Title")

像这样:

public static class MyDialogFragment extends DialogFragment {
    ...
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Set title for this dialog
        getDialog().setTitle("My Dialog Title");

        View v = inflater.inflate(R.layout.mydialog, container, false);
        // ...
        return v;
    }
    // ...
}
Run Code Online (Sandbox Code Playgroud)

  • 是的,确实是getDialog().setTitle()可以解决问题.在查看解决方案后,以这种方式工作确实很有意义但由于某种原因我希望调用将标题设置在DialogFragment类本身上(定义setStyle()和DialogFragment.STYLE_NO_TITLE的地方).非常感谢你的解决方案. (6认同)
  • 另请注意,您无法在片段的onCreate()方法中设置对话框标题,因为尚未创建对话框:) (5认同)
  • @Rob Holmes我想从对话框类的外部设置标题(我在其中创建实例).即MyDialogFragment myFragment = new MyDialogFragment(); myFragment.getDialog()的setTitle( "myTitle"); myFragment.show(getFragmentManager(),"myTitle"); 但是,似乎getDialog()此时返回null.还有另一种方法可以从这里设置标题(没有制作我自己的setTitle methdo)吗? (2认同)

Jas*_*ley 74

是否覆盖onCreateDialog并直接在Dialog作品上设置标题?像这样:

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    Dialog dialog = super.onCreateDialog(savedInstanceState);
    dialog.setTitle("My Title");
    return dialog;
}
Run Code Online (Sandbox Code Playgroud)

  • 您的解决方案更好,因为片段不仅可以在对话框中使用 (8认同)

ban*_*ing 14

Jason的回答过去常常适合我,但是现在它需要以下添加才能获得标题.

首先,在MyDialogFragment的onCreate()方法中,添加:

setStyle(DialogFragment.STYLE_NORMAL, R.style.MyDialogFragmentStyle);

然后,在styles.xml文件中,添加:

<style name="MyDialogFragmentStyle" parent="Theme.AppCompat.Light.Dialog.Alert">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">false</item>
    <item name="android:windowActionBar">false</item>
    <item name="android:windowNoTitle">false</item>
</style>
Run Code Online (Sandbox Code Playgroud)

经过几个小时尝试不同的事情,这是唯一一个为我做了诀窍的人.

注意 - 您可能需要将其更改Theme.AppCompat.Light.Dialog.Alert为其他内容以匹配主题的样式.