问题
This should be a simple task, but for some reason I can find a way to set the title of a DialogFragment. (I am setting the dialog contents using onCreateView
overload).
The default style leaves a place for the title, but I can't find any method on the DialogFragment
class to set it.
The title is somehow magically set when the onCreateDialog
method is used to set the contents, so I wonder if this is by design, or there is a special trick to set it when using the onCreateView
overload.
回答1:
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;
}
// ...
}
回答2:
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;
}
回答3:
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.
回答4:
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);
}
}
回答5:
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();
}
来源:https://stackoverflow.com/questions/5193722/how-to-set-the-title-of-dialogfragment