类似于Ban Geoengineering's answer,但有一些修改,因此我没有编写DialogFragment 中使用的特定主题,而是覆盖DialogFragments 在我的styles.xml 中使用的默认样式。
在androidx.fragment.app.DialogFragment中设置标题。
class EditBatteryLevelFragment:DialogFragment(),SelfClosingFragment.Host
{
override fun onCreateView(
inflater:LayoutInflater,container:ViewGroup?,savedInstanceState:Bundle?
):View
{
// set dialog title
requireDialog().setTitle(R.string.edit_battery_level__title)
// .....
return someView
}
}
在styles.xml 的应用主题中,覆盖android:dialogTheme,这是DialogFragment 实例使用的默认样式。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="AppTheme" parent="Theme.MaterialComponents">
<!-- BONUS READING: override material colors here, too https://material.io/develop/android/theming/color -->
<!-- override DialogFragment theme of those spawned by activities with this theme -->
<item name="android:dialogTheme">@style/AppTheme.Dialog</item>
</style>
<!-- ... -->
同样在styles.xml 中,声明DialogFragment 实例将使用的对话框主题。此样式继承自 ThemeOverlay 很重要,这样它才能保留您应用的主题颜色。
<!-- ... -->
<!-- define the style for your dialog -->
<style name="AppTheme.Dialog" parent="ThemeOverlay.MaterialComponents.Dialog">
<!-- add a minimun width to the dialog, so it's not too narrow -->
<item name="android:windowMinWidthMajor">@dimen/abc_dialog_min_width_major</item>
<item name="android:windowMinWidthMinor">@dimen/abc_dialog_min_width_minor</item>
<!-- display the title for dialogs -->
<item name="android:windowNoTitle">false</item>
</style>
</resources>
确保生成DialogFragment 的活动正在使用定义的AppTheme。