Android:将不同的主题应用于一个 Activity 的 fragment

标签 android android-layout

我想做的事:

我希望 MainActivity 的每个 Fragment 使用不同的主题,以便 ActionBar 具有不同的背景颜色,具体取决于可见的 Fragment。

情况:

我创建了一个使用 Tabs + Swipe Navigation 的 MainActivity。我添加了 7 个标签(=7 个 fragment )。我创建了一个仅应用于第一个 Fragment (fragment_main_1) 的主题。

这里是主题:

<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="Blue" parent="android:Theme.Holo.Light">
    <item name="android:actionBarStyle">@style/Blue.ActionBarStyle</item>
</style>

<style name="Blue.ActionBarStyle" parent="android:Widget.Holo.Light.ActionBar">
    <item name="android:titleTextStyle">@style/Blue.ActionBar.TitleTextStyle</item>
    <item name="android:background">#33B5E5</item>
</style>

<style name="Blue.ActionBar.TitleTextStyle" parent="android:TextAppearance.Holo.Widget.ActionBar.Title">
    <item name="android:textColor">#FFFFFF</item>
</style>
</resources>

再创建 6 个主题后,应该可以在 ActionBar 自动更改其背景颜色时滑动浏览选项卡。

什么不起作用:

将这些行(我在 stackoverflow 上找到)添加到 Fragment1.java:

// create ContextThemeWrapper from the original Activity Context with the custom theme
final Context contextThemeWrapper = new ContextThemeWrapper(getActivity(), R.style.Blue);

// clone the inflater using the ContextThemeWrapper
LayoutInflater localInflater = inflater.cloneInContext(contextThemeWrapper);

// inflate the layout using the cloned inflater, not default inflater
return localInflater.inflate(R.layout.fragment_main_1,container, false);

希望你能帮助我:) 谢谢。

最佳答案

很多 fragment (如PreferenceFragment)直接从Fragment.getContext()方法返回的Context中读取样式属性,所以你可能也需要覆盖它:

private var themedContext: Context? = null

override fun onAttach(context: Context) {
    super.onAttach(context).also {
        themedContext = ContextThemeWrapper(context, R.style.ThemeForThisFragment)
        // if you want to apply a theme overlay:
        // themedContext.theme.applyStyle(R.style.MyThemeOverlay, true)
    }
}

override fun onDetach() {
    super.onDetach()
    themedContext = null
}

override fun getContext(): Context? {
    return themedContext ?: super.getContext()
}

关于Android:将不同的主题应用于一个 Activity 的 fragment ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15663613/

相关文章:

android - app_release.apk 的 Google oauth 问题,app_debug.apk 工作正常

java - 3 旋转器不工作

Android:具有特定尺寸的背景?

android - 没有足够的空间来展示广告!想要 : <480, 75>,有 : <454, 90>

android - 如何为所有 Activity 创建通用的 Android XML 布局

android - 文件 0000000000000001.db 是什么?

android - ImageView 上方的按钮?

android - 我的 CardView 和 TextInputLayout 有问题

android - 在 R.attr 中找到正确的样式

android - 剪切 ListView Android 中的文本