Android:将不同的主题应用于一个活动的片段

25

我想要做什么:

我希望我的MainActivity中的每个Fragment使用不同的主题,这样ActionBar的背景颜色根据当前可见的Fragment不同而变化。

现状:

我创建了一个使用选项卡和滑动导航的MainActivity。我添加了7个选项卡(= 7个Fragments)。我创建了一个主题,仅应用于第一个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个主题后,就可以通过滑动选项卡来自动更改操作栏的背景色。

没有成功的方法:

将这些代码行(我在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);

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


不,我放弃了那个项目 :( - Jonas
有人找到这个问题的答案了吗? - Marc-André Therrien
这个回答可能会有所帮助:http://stackoverflow.com/a/23636484/1083128,基本上,这一切都是关于幻觉的:p - Mia
五年过去了,仍然没有明确的答案... - Denny
显示剩余2条评论
2个回答

3

许多片段(例如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()
}

这很棒,因为您可以使用附加到片段的上下文创建新的窗口,例如对于对话框,最好首先重写getContext。要更改片段视图本身的样式,只需在onCreateView中使用inflater.cloneInContext(context)克隆上下文来填充视图即可。 - Reza Mohammadi

2
尝试使用LayoutInflater localInflater = inflater.from(contextThemeWrapper);代替。

3
谢谢您的快速回复,但是那并没有帮助到我 :( - Jonas

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