Android DialogFragment 标题未显示

42

创建自定义 DialogFragment 时,我使用以下方式设置标题:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.fragment_dialog_add, container, false);      

    // Setting title here
    getDialog().setTitle("Add New");

    return v;
}

对于 API 版本低于 23,上述代码可以正常工作。但在 API 23 中,标题根本就不显示。

有任何想法原因吗?如何使标题在 API 23 上显示?

3个回答

58

通过将以下内容添加到styles.xml中解决:

<item name="android:dialogTheme">@style/CustomDialog</item>

<style name="CustomDialog" parent="@style/Theme.AppCompat.Light.Dialog">
    <item name="android:windowNoTitle">false</item>
</style>

2
谢谢!我都快抓狂了。不确定为什么在API 23之后windowNoTitle似乎默认为true,但感谢您的修复! - AdamMc331
7
确实不理解为什么他们在API23中更改了这个。 - Sudara
2
使用 parent="@style/Theme.AppCompat.Dialog" 来创建暗色对话框。 - Yani2000
我的基础主题扩展了Theme.AppCompat.DayNight.NoActionBar。如果我覆盖它,那么背景、控件颜色都会改变。你能提供其他解决方案吗? - gopalanrc

47

在你的样式表中:

<style name="CustomDialog" parent="@style/Theme.AppCompat.Light.Dialog">
    <item name="android:windowNoTitle">false</item>
</style>

如果您的对话框是一个片段:

MyFragment myFragment = new MyFragment();
myFragment.setStyle(DialogFragment.STYLE_NORMAL, R.style.CustomDialog);

-1

我使用.setMessage而不是.setTitle来解决问题。我知道它们的外观不同,但在我的情况下,我只需要给用户一个提示。


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