更改片段更改主题

时间:2019-06-17 11:28:31

标签: java android fragment themes

我需要动态更改fragment主题,我尝试使用此代码,但不适用于onCreateonCreateView()

getActivity().setTheme(R.style.ActionMode);

我如何从fragment设置主题?

1 个答案:

答案 0 :(得分:1)

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);
}