【问题标题】:Android: Apply different themes to fragments of one activityAndroid:将不同的主题应用于一个活动的片段
【发布时间】:2023-03-06 00:19:02
【问题描述】:

我想做的事:

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

情况:

我创建了一个使用 Tabs + Swipe Navigation 的 MainActivity。我添加了 7 个标签(=7 个片段)。我创建了一个仅应用于第一个 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);

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

【问题讨论】:

  • 您找到解决方案了吗?
  • 不,我放弃了那个项目 :(
  • 有人找到这个问题的答案吗?
  • 有人解决这个问题吗?
  • 这个答案stackoverflow.com/a/23636484/1083128 可能会有所帮助,基本上,这都是关于幻觉的:p

标签: android android-layout


【解决方案1】:

许多片段(例如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。要更改片段视图本身的样式,您只需使用 inflater.cloneInContext(context) 对 onCreateView 中的视图进行膨胀。
【解决方案2】:

改用LayoutInflater localInflater = inflater.from(contextThemeWrapper);

【讨论】:

  • 感谢您的快速回复,但这并没有帮助:(
猜你喜欢
  • 2023-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-04
  • 2017-01-16
  • 2018-03-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多