根据使用Android中的片段更改活动主题

时间:2014-05-13 15:44:35

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

我有一个在多个片段之间切换的活动。此活动具有默认样式,但是当我更改为某些特定片段时,我希望它更改样式。我做了一些研究,我得到了这个代码,我在片段的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);

此代码仅在重新启动活动时有效(例如:如果我将设备旋转,则根据需要将其更新为新样式)。我认为不可能在重新创建活动之间切换样式,或者我错了吗?

1 个答案:

答案 0 :(得分:2)

从技术上讲:不。

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

  

此代码仅在重新启动活动时有效(例如:如果我旋转   设备它根据我的需要更新到新风格)。我认为事实并非如此   可以在不重新创建活动或我的样式之间切换   我错了?

由于旋转包括重新开展活动,这就是为什么"工作"。

但是......有一个名为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:

为链接帖添加了更多解释

相关问题