首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Android:将不同的主题应用于一个活动的片段

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

Stack Overflow用户
提问于 2013-03-28 00:08:13
回答 2查看 14K关注 0票数 25

我想做什么:

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

情境:

我创建了一个使用Tabs + Swipe导航的MainActivity。我添加了7个Tabs (=7个片段)。我创建了一个主题,它应该只应用于第一个片段(fragment_main_1)。

下面是主题:

代码语言:javascript
复制
<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:

代码语言:javascript
复制
// 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);

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

EN

回答 2

Stack Overflow用户

发布于 2020-07-07 17:30:30

许多片段(如PreferenceFragment)直接从Fragment.getContext()方法返回的Context读取样式属性,因此您可能也需要覆盖它:

代码语言:javascript
复制
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()
}
票数 3
EN

Stack Overflow用户

发布于 2013-03-28 00:13:17

请尝试使用LayoutInflater localInflater = inflater.from(contextThemeWrapper);

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15663613

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档