片段主题

时间:2015-03-05 16:59:00

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

我有一个片段,可以在应用程序的两个不同位置使用。根据片段的使用位置,我需要它看起来不同。

更改主要包括文本颜色,背景和某些元素可见性。我希望能够使用相同的布局和片段,但根据其使用位置的不同主题。我不能依赖于不同的主题,因为片段可能需要在同一活动中的两个主题中加载。

无论如何要做到这一点?另外我知道在5.0中我们现在可以在任何视图上指定主题属性。这个功能是在appcompat lib中找到的吗?

任何解决方案都需要在api 16及更高版本上运行。

谢谢, 森

1 个答案:

答案 0 :(得分:0)

您可以使用ContextThemeWrapper: http://developer.android.com/reference/android/view/ContextThemeWrapper.html

在onCreateView中,您可以

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        final Context contextThemeWrapper = new ContextThemeWrapper(getActivity(), R.style.yourtheme);
        LayoutInflater localInflater = inflater.cloneInContext(contextThemeWrapper);
        return localInflater.inflate(R.layout.yourfragment, container, false);
    }
相关问题