How to set the title of DialogFragment?

被刻印的时光 ゝ 提交于 2019-11-28 16:35:44
Rob Holmes

You can use getDialog().setTitle("My Dialog Title")

Just like this:

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;
    }
    // ...
}

Does overriding onCreateDialog and setting the title directly on the Dialog work? Like this:

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    Dialog dialog = super.onCreateDialog(savedInstanceState);
    dialog.setTitle("My Title");
    return dialog;
}
ban-geoengineering

Jason's answer used to work for me, but now it needs the following additions to get the title to show.

Firstly, in your MyDialogFragment's onCreate() method, add:

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

Then, in your styles.xml file, add:

<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>

After hours of trying different things, this is the only one that has done the trick for me.

NB - You may need to change the Theme.AppCompat.Light.Dialog.Alert to something else in order to match the style of your theme.

DialogFragment could be represented as dialog and as Activity. Use code below that would work properly for both

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    if (getShowsDialog()) {
        getDialog().setTitle(marketName);
    } else {
        getActivity().setTitle(marketName);
    }
}

You can take a look at the official docs. The way i did is like this:

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity())
            .setTitle("My Title");
    LayoutInflater inflater = getActivity().getLayoutInflater();
    View view = inflater.inflate(R.layout.my_layout, null);
    builder.setView(view);

    return builder.create();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!