【问题标题】:Change Activity theme deppending on fragment in use Android根据使用 Android 的片段更改 Activity 主题
【发布时间】:2014-05-13 15:44:35
【问题描述】:

我有一个在多个片段之间切换的活动。此活动具有默认样式,但是当我更改为某些特定片段时,我希望它更改样式。我做了一些研究,得到了在片段的 onCreateView() 中运行的代码:

// create ContextThemeWrapper from the original Activity Context with the custom theme
    Context context = new ContextThemeWrapper(getActivity(), R.style.GreyTheme);
    // clone the inflater using the ContextThemeWrapper
    LayoutInflater localInflater = inflater.cloneInContext(context);
    // inflate using the cloned inflater, not the passed in default 

    View rootView = localInflater.inflate(R.layout.my_layout, container, false);

此代码仅在活动重新启动时才有效(例如:如果我旋转设备,它会根据需要更新为新样式)。我认为在不重新创建活动的情况下无法在样式之间切换还是我错了?

【问题讨论】:

  • 我发现这适用于在 API23 的片段中膨胀的本地视图,尚未测试其他 API 版本。
  • 还有 API17 :)

标签: android android-fragments android-activity android-theme android-styles


【解决方案1】:

从技术上讲:没有。

如果 Activity 已创建,则无法更改当前主题。

此代码仅在活动重新启动时才有效(例如:如果我旋转 设备会根据我的需要更新为新样式)。我认为不是 无需重新创建活动或 am 就可以在样式之间切换 我错了吗?

由于轮换包括对活动的娱乐,这就是为什么“工作”的原因。

但是……有一个名为 Pocket(如果我没记错的话,还有 Press 和 Firefox)的应用程序以一种巧妙的方式做到了这一点。

怎么做?

基本上诀窍在于这个公式:

Base Color1 + Middle Color = Theme Color 1

Base Color2 + Middle Color = Theme Color 2

请记住,中间色是相同的。对于基础颜色,您必须将其放在包含您的应用实例的 Window 中,如下所示:

getWindow().setBackgroundDrawable(new ColorDrawable(isLight ? Color.WHITE : Color.BLACK));

因此当与中间色结合时,会给你两个不同的主题。

在这里你可以看到你是如何做到的(它很好地解释了这个概念):

http://sriramramani.wordpress.com/2012/12/06/runtime-theme-change/

编辑 1:

为链接帖子添加了更多解释

【讨论】:

  • 很好的答案.. 非常感谢
猜你喜欢
  • 1970-01-01
  • 2020-05-28
  • 1970-01-01
  • 2017-03-30
  • 2017-10-01
  • 1970-01-01
  • 2015-03-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多