gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 23:07:15 26 4
gpt4 key购买 nike

我想做的事:

我希望 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com