当Fragment变化时更改主题

3
我需要动态更改碎片的主题,我尝试了这段代码,但它在onCreate或onCreateView()中不起作用。
getActivity().setTheme(R.style.ActionMode);

我怎样才能从fragment中设置主题?
1个回答

3
onCreateView() 方法中,你需要创建一个 ContextThemeWrapper 并从其中膨胀主题样式,像下面一样:
@Override
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
    //create ContextThemeWrapper from the original Activity Context with the custom theme
    Context context = new ContextThemeWrapper(getActivity(), R.style.your_Custom_Theme);
    //clone the inflater using the ContextThemeWrapper
    LayoutInflater localInflater = inflater.cloneInContext(context);
    //inflate using the cloned inflater, not the passed in default
    return localInflater.inflate(R.layout.your_layout, container, false);
}

2
谢谢您的回复,我尝试了这段代码,但它对我没有起作用。 - tecn603
请问您遇到了什么问题?让我们分享一下您的代码,这样我们就可以帮助您解决。 - Android

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接