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

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


如何从fragment设置主题?

最佳答案

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

07-24 09:26